WindowMain.SpriteToTGA:
Sub SpriteToTGA(IsCC1File As Boolean, IsSoldierFile As Boolean)
  dim InFile As BinaryStream
  dim OutFile, MaskOutFile As BinaryStream
  dim ReportFile As BinaryStream
  dim OutPath As String
  dim OutName, MaskOutName As String
  dim dlg1 As OpenDialog
  dim dlg2 As SelectFolderDialog
  dim f1, f2, f3, fMask As FolderItem
  dim count, i, j, filecount As Integer
  dim WhereWeAre As Integer  // for debugging purpose only
  dim trashThisPixel As Integer
  dim trashPixelCount As Integer
  dim trashPixelList As String
  dim colorPixel As Integer
  dim cRed, cGreen, cBlue As Integer
  dim whiteColorPixelCount As Integer
  dim whiteColorPixelList As String
  dim b0, b1 As Integer
  dim pixelswritten As Integer
  dim CR, TAB As String
  dim GoToPosition As Integer
  
  dim FormatStringCC2 As String
  dim FormatStringCC4 As String
  
  // header description of Sprite-File
  dim myFormatId As String
  dim myVersionId As Integer
  dim myDirectoryHeader As Integer    // must be 1000
  dim myNumberOfEntries As Integer   // for sequence 1001
  dim myNumberOfStaticAnim As Integer // for sequence 1002
  dim myNumberOfDirectionAnim As Integer // for sequence 1003
  dim myColorDepth As Integer // or number of directions ??
  dim mySpriteTableHeader As Integer   // must be 1001
  
  // header description of a single entry
  dim myWidth As Integer    // in pixel
  dim myHeight As Integer
  dim myHotspotX As Integer
  dim myHotspotY As Integer
  dim myEntrySize As Integer      // counted in bytes
  dim myLines(60000) As Integer  // line offsets
  
  dim myEntryBytesRead As Integer
  
  // color look up table (CLUT) of CC1
  dim CC1red(255) As Integer
  dim CC1green(255) As Integer
  dim CC1blue(255) As Integer
  dim myClutPic As Picture
  
  // the ouput colors we will use
  dim ColorTransparency As Integer
  dim ColorShadow As Integer
  dim ColorFillarea As Integer
  dim Color2ndShadow As Integer
  dim ColorMask(9) As Integer
  
  // sprite sequence lists
  dim spritenumbers As Integer
  dim sequenceindicator As Integer
  
  // constant defining
  FormatStringCC2 = "SPRI"   // for CC2 and CC3
  FormatStringCC4 = "IRPS"   // reverse byte format in CC4/CC5/CCM/RtB
  ColorTransparency = &h7FFF // as suggested by Cpl_Filth
  ColorShadow = &h4EE0          // as suggested by Cpl_Filth
  ColorFillarea = &h7D91         // new value by Mafi
  Color2ndShadow = &h7FE1             // new value by Mafi
  for i = 0 to 9
    ColorMask(i) = (i * 1500) + 5000
  next
  
  ColorTransparency = App.ColorToTGAvalue(App.gSpecialColor(0))
  ColorShadow = App.ColorToTGAvalue(App.gSpecialColor(1))
  ColorFillarea = App.ColorToTGAvalue(App.gSpecialColor(2))
  Color2ndShadow = App.ColorToTGAvalue(App.gSpecialColor(3))
  
  if (CC1clut125 <> NIL) then
    myClutPic = NewPicture(CC1clut125.Width, CC1clut125.Height, 32)
    if  (myClutPic <> NIL) and (myClutPic.Graphics <> NIL) then
      myClutPic.Graphics.DrawPicture(CC1clut125, 0, 0)
      for i = 0 to 255
        CC1red(i) = myClutPic.Graphics.Pixel(((i MOD 16) * 16) + 8, ((i \ 16) * 16) + 8).red
        CC1green(i) = myClutPic.Graphics.Pixel(((i MOD 16) * 16) + 8, ((i \ 16) * 16) + 8).green
        CC1blue(i) = myClutPic.Graphics.Pixel(((i MOD 16) * 16) + 8, ((i \ 16) * 16) + 8).blue
      next
    end
  end
  
  //start user interface
  dlg1 = New OpenDialog
  if IsSoldierFile then
    dlg1.Title = "Select a CC-Soldier-Sprite-File for Input"
  else
    dlg1.Title = "Select a CC-Sprite-File for Input"
  end
  dlg1.ActionButtonCaption = "Select"
  if IsCC1File then
    dlg1.PromptText = "select a CC1-sprite-file to be splitted into TARGA graphics files."
  else
    dlg1.PromptText = "select a sprite-file to be splitted into TARGA graphics files."
  end
  dlg1.Filter = "any file"
  f1 = dlg1.ShowModal
  
  if (f1 <> NIL) then
    
    dlg2 = New SelectFolderDialog
    dlg2.Title = "Select Folder for new Files"  
    dlg2.ActionButtonCaption = "Select"
    dlg2.PromptText = "select folder to store the new files."
    dlg2.Filter = "any file"
    f2 = dlg2.ShowModal
    
    if (f2 <> NIL) then
      OutPath = f2.AbsolutePath
      #if TargetWin32
        if (Right(OutPath, 1) <> "\") then
          OutPath = OutPath + "\"
        end
      #else
        if (Right(OutPath, 1) <> ":") then
          OutPath = OutPath + ":"
        end
      #endif
      
      InFile = f1.OpenAsBinaryFile(FALSE)
      if (InFile <> NIL) then
        if (not InFile.eof) then
          InFile.LittleEndian = FALSE   // its a Mac-born file perhaps
          // first read the header (20 bytes)
          
          myFormatId = InFile.Read(4)     // four bytes, should be "SPRI"
          if (Uppercase(myFormatId) = Uppercase(FormatStringCC2)) then
            InFile.LittleEndian = FALSE   // essential, its a Mac-born file, valid for CC2 and CC3
            myFormatId = FormatStringCC2
          elseif (Uppercase(myFormatId) = Uppercase(FormatStringCC4)) then
            InFile.LittleEndian = TRUE   // essential, its a PC-born file, valid for CC4, CC5, CCM and RoadToBaghdad
            myFormatId = FormatStringCC4
          else
            MsgBox "file format may be wrong, header found: " + myFormatId
          end
          
          if not InFile.eof then
            myVersionId = InFile.ReadLong     REM four bytes
          end
          if not InFile.eof then
            myDirectoryHeader = InFile.ReadShort   REM two bytes
          end
          if not InFile.eof then
            myNumberOfEntries = InFile.ReadShort    REM two bytes
          end
          if not InFile.eof then
            myNumberOfStaticAnim = InFile.ReadShort   REM two bytes
          end
          if not InFile.eof then
            myNumberOfDirectionAnim = InFile.ReadShort   REM two bytes
          end
          if not InFile.eof then
            myColorDepth = InFile.ReadShort   REM two bytes
          end
          if not InFile.eof then
            mySpriteTableHeader = InFile.ReadShort   REM two bytes
          end
          
          if (not InFile.eof) and (mySpriteTableHeader = 1001) then
            ProgressBarExtract.Visible = TRUE
            ProgressBarExtract.Value = 0
            ProgressBarExtract.Maximum = myNumberOfEntries
            ProgressBarExtract.Refresh
            
            GoToPosition = InFile.Position    // **** new v2.6: necessary for buggy CC3-Terrain file
            // I hope there are no additional blank bytes between header and entries
            trashPixelList = ""  // **** new v2.7.2: for whole-file bug-report
            whiteColorPixelList = ""   // **** new in v2.7.3: for additional bug reports
            
            for count = 1 to myNumberOfEntries
              trashPixelCount = 0  // **** new v2.7.2: for single sprite bug-report
              whiteColorPixelCount = 0   // **** new in v2.7.3: for additional bug reports
              ProgressBarExtract.Value = count
              ProgressBarExtract.Refresh   // **** new in v2.7.3
              // read each entry
              // first: the header: 12 bytes
              if not InFile.eof then
                myWidth = InFile.ReadShort   // two bytes
              end
              if not InFile.eof then
                myHeight = InFile.ReadShort   // two bytes
              end
              if not InFile.eof then
                myHotSpotX = InFile.ReadShort   // two bytes
              end
              if not InFile.eof then
                myHotSpotY = InFile.ReadShort   // two bytes
              end
              if not InFile.eof then
                myEntrySize = InFile.ReadLong   // four bytes
              end
              
              myEntryBytesRead = 0
              
              for i = 1 to myHeight   // (myHeight * 2) bytes
                myLines(i) = InFile.ReadShort    // two bytes per line of the image
                myEntryBytesRead = myEntryBytesRead + 2
              next
              
              // create output filename
              if RadioButtonCountZero.Value then
                filecount = count - 1
              else
                filecount = count
              end
              OutName = OutPath + "Image"
              MaskOutName = OutPath + "Mask"
              if (filecount < 10) then
                OutName = OutName + "0"
                MaskOutName = MaskOutName + "0"
              end
              if (filecount < 100) then
                OutName = OutName + "0"
                MaskOutName = MaskOutName + "0"
              end
              if (filecount < 1000) then
                OutName = OutName + "0"
                MaskOutName = MaskOutName + "0"
              end
              OutName = OutName + Str(filecount) + "." + Str(myHotspotX) + "." + Str(myHotspotY) + ".tga"
              MaskOutName = MaskOutName + Str(filecount) + "." + Str(myHotspotX) + "." + Str(myHotspotY) + ".tga"
              
              // create output file
              f2 = GetFolderItem(OutName)
              fMask = NIL
              if IsSoldierFile then
                fMask = GetFolderItem(MaskOutName)
              end
              
              if (f2 <> NIL) then
                MaskOutFile = NIL
                
                #if TargetWin32
                  OutFile = f2.CreateBinaryFile("")
                #else
                  OutFile = f2.CreateBinaryFile("image/x-targa")
                #endif
                
                if (OutFile <> NIL) then
                  
                  OutFile.LittleEndian = TRUE   REM because it is a PC-like TARGA graphics file
                  
                  if IsSoldierFile and (fMask <> NIL) then
                    #if TargetWin32
                      MaskOutFile = fMask.CreateBinaryFile("")
                    #else
                      MaskOutFile = fMask.CreateBinaryFile("image/x-targa")
                    #endif
                    MaskOutFile.LittleEndian = TRUE   REM because it is a PC-like TARGA graphics file
                  end
                  
                  // first: the TARGA-header
                  OutFile.WriteShort(0)     // no ID, no color map
                  OutFile.WriteShort(2)     // Image Type: uncompressed True-Color
                  OutFile.WriteLong(0)      // no color map
                  OutFile.WriteLong(0)      // image origin lower left
                  OutFile.WriteShort(myWidth)
                  OutFile.WriteShort(myHeight)
                  OutFile.WriteByte(16)   // Color Depth 16-bit
                  if RadioButtonTopDown.Value then
                    OutFile.WriteByte(33)   // Image Descriptor: ignore 1 bit, top-to-bottom and left-to-right pixel orientation
                  else
                    OutFile.WriteByte(1)   // Image Descriptor: ignore 1 bit, bottom-to-top and left-to-right pixel orientation
                  end
                  if IsSoldierFile and (MaskOutFile <> NIL) then
                    MaskOutFile.WriteShort(0)     // no ID, no color map
                    MaskOutFile.WriteShort(2)     // Image Type: uncompressed True-Color
                    MaskOutFile.WriteLong(0)      // no color map
                    MaskOutFile.WriteLong(0)      // image origin lower left
                    MaskOutFile.WriteShort(myWidth)
                    MaskOutFile.WriteShort(myHeight)
                    MaskOutFile.WriteByte(16)   // Color Depth 16-bit
                    if RadioButtonTopDown.Value then
                      MaskOutFile.WriteByte(33)   // Image Descriptor: ignore 1 bit, top-to-bottom and left-to-right pixel orientation
                    else
                      MaskOutFile.WriteByte(1)   // Image Descriptor: ignore 1 bit, bottom-to-top and left-to-right pixel orientation
                    end
                  end
                  
                  // now the datas, processing the line offset table
                  for i = 1 to myHeight
                    if (BitWiseAnd(myLines(i), &hFFFF) = &hFFFF) or (myLines(i) = -1) then  REM complete line totally blank = white = transparent
                      for j = 1 to myWidth
                        OutFile.WriteShort( ColorTransparency )
                        if IsSoldierFile and (MaskOutFile <> NIL) then
                          MaskOutFile.WriteShort( ColorTransparency )
                        end
                      next
                    else  REM line contains pixels
                      pixelswritten = 0
                      do
                        b0 = AscB( InFile.Read(1) )
                        myEntryBytesRead = myEntryBytesRead + 1
                        select case b0
                          
                        case &hFF     // color pixel is coming
                          b1 = AscB( InFile.Read(1) )
                          myEntryBytesRead = myEntryBytesRead + 1
                          // number of pixels is stored in b1
                          // if (b1 > myWidth) then dont correct this, otherwise pixels will be not all read!
                          //     MsgBox "Error in sprite #" + Str(filecount) + ": number of color pixels execeeds line width."
                          //    b1 = myWidth
                          // end
                          
                          if IsCC1File then // new since v2.8.2
                            for j = 1 to b1
                              if (pixelswritten < myWidth) then  // because there is an error inside the Terrain-file for pic#61 (8 pixels too much)
                                // every input pixel is always 8-bit wide !
                                colorPixel = InFile.ReadByte
                                colorPixel = App.ColorToTGAvalue(RGB(CC1red(colorPixel), CC1green(colorPixel), CC1blue(colorPixel)))
                                OutFile.WriteShort ( colorPixel )
                                if IsSoldierFile and (MaskOutFile <> NIL) then
                                  MaskOutFile.WriteShort( ColorTransparency )
                                end
                                if BitWiseAnd(colorPixel, &hFF) = ColorTransparency then   // **** new in v2.7.3
                                  whiteColorPixelCount = whiteColorPixelCount + 1
                                end
                                myEntryBytesRead = myEntryBytesRead + 1
                                pixelswritten = pixelswritten + 1
                              else
                                trashThisPixel = InFile.Readbyte    // read this one bytes to avoid miss-interpreting of pixel datas as control bytes
                                myEntryBytesRead = myEntryBytesRead + 1
                                trashPixelCount = trashPixelCount + 1
                              end
                            next
                          else
                            for j = 1 to b1
                              if (pixelswritten < myWidth) then  // because there is an error inside the Terrain-file for pic#61 (8 pixels too much)
                                // every pixel is always 16-bit wide !
                                // OutFile.WriteShort( InFile.ReadShort )  // take the datas as they are
                                colorPixel = InFile.ReadShort
                                OutFile.WriteShort ( colorPixel )
                                if IsSoldierFile and (MaskOutFile <> NIL) then
                                  MaskOutFile.WriteShort( ColorTransparency )
                                end
                                if BitWiseAnd(colorPixel, &hFFFF) = ColorTransparency then   // **** new in v2.7.3
                                  whiteColorPixelCount = whiteColorPixelCount + 1
                                end
                                myEntryBytesRead = myEntryBytesRead + 2
                                pixelswritten = pixelswritten + 1
                              else
                                // **** new in v2.7.1
                                trashThisPixel = InFile.ReadShort    // read this two bytes to avoid miss-interpreting of pixel datas as control bytes
                                myEntryBytesRead = myEntryBytesRead + 2
                                // dont write this pixel.
                                // but remember the amount, **** new in v2.7.2
                                trashPixelCount = trashPixelCount + 1
                              end
                            next
                          end
                          
                        case &h00     // transparency pixel is coming
                          b1 = AscB( InFile.Read(1) )
                          myEntryBytesRead = myEntryBytesRead + 1
                          // number of pixels is stored in b1
                          // write this amount of transparent pixels
                          for j = 1 to b1
                            OutFile.WriteShort( ColorTransparency )
                            if IsSoldierFile and (MaskOutFile <> NIL) then
                              MaskOutFile.WriteShort( ColorTransparency )
                            end
                            pixelswritten = pixelswritten + 1
                          next
                          
                        case &hF5    // shadow pixel is coming
                          b1 = AscB( InFile.Read(1) )
                          myEntryBytesRead = myEntryBytesRead + 1
                          // write this amount of shadow pixels
                          for j = 1 to b1
                            OutFile.WriteShort( ColorShadow )
                            if IsSoldierFile and (MaskOutFile <> NIL) then
                              MaskOutFile.WriteShort( ColorTransparency )
                            end
                            pixelswritten = pixelswritten + 1
                          next
                          
                        case &hF7     // special pixel for "fill-area" purpose, used by crosshairs in Terrain
                          b1 = AscB( InFile.Read(1) )
                          myEntryBytesRead = myEntryBytesRead + 1
                          // write this amount of special pixels
                          for j = 1 to b1
                            OutFile.WriteShort( ColorFillarea )  // lilac
                            if IsSoldierFile and (MaskOutFile <> NIL) then
                              MaskOutFile.WriteShort( ColorTransparency )
                            end
                            pixelswritten = pixelswritten + 1
                          next
                          
                        case &hF9     // special pixel for "white" purpose, used by big trees in Terrain
                          b1 = AscB( InFile.Read(1) )
                          myEntryBytesRead = myEntryBytesRead + 1
                          // write this amount of special pixels
                          for j = 1 to b1
                            OutFile.WriteShort( Color2ndShadow )  // yellow
                            if IsSoldierFile and (MaskOutFile <> NIL) then
                              MaskOutFile.WriteShort( ColorTransparency )
                            end
                            pixelswritten = pixelswritten + 1
                          next
                          
                        case &hED      // line end specifier - fill the rest of the line with white pixels
                          for j = 1 to myWidth - pixelswritten
                            OutFile.WriteShort( ColorTransparency )
                            if IsSoldierFile and (MaskOutFile <> NIL) then
                              MaskOutFile.WriteShort( ColorTransparency )
                            end
                          next
                          
                        else
                          if (b0 >= &hC0) and (b0 <= &hC9) then   // soldier pixel is coming, not in CC1
                            b1 = AscB( InFile.Read(1) )
                            myEntryBytesRead = myEntryBytesRead + 1
                            // number of pixels is stored in b1
                            for j = 1 to b1
                              // provisional: treat them like color pixels, but should be reported as mask
                              // ***** this must be debugged next time!! -> reporting to mask must be added!!
                              if (pixelswritten < myWidth) then
                                // every pixel is always 16-bit wide !
                                if IsSoldierFile and (MaskOutFile <> NIL) then
                                  MaskOutFile.WriteShort( InFile.ReadShort )  // take the datas as they are
                                  OutFile.WriteShort( ColorMask(b0 - &hC0) )
                                else
                                  OutFile.WriteShort( InFile.ReadShort )  // take the datas as they are
                                end
                                myEntryBytesRead = myEntryBytesRead + 2
                                pixelswritten = pixelswritten + 1
                              else
                                // **** new in v2.7.1
                                trashThisPixel = InFile.ReadShort    // read this two bytes to avoid miss-interpreting of pixel datas as control bytes
                                myEntryBytesRead = myEntryBytesRead + 2
                                // dont write this pixel.
                                // but remember the amount, **** new in v2.7.2
                                trashPixelCount = trashPixelCount + 1
                              end
                            next
                          else
                            // dont report this to avoid multiple MsgBoxes without aborting
                            //WhereWeAre = InFile.Position
                            //MsgBox "at input-file-offset " + Hex(WhereWeAre - 1) + "h - error in sprite #" + Str(filecount) + ", unknown line descriptor found: " + Hex(b0) + "h"
                          end
                        end select
                      loop until (b0 = &hED)
                    end
                  next
                  
                  // special for CC4/CC5/CCM/RtB-Terrain and *.spr file: trailing zero byte must be read after last line
                  if (myFormatId = FormatStringCC4) and (not IsCC1File) then
                    while (myEntryBytesRead < myEntrySize)
                      b0 = AscB( InFile.Read(1) )
                      myEntryBytesRead = myEntryBytesRead + 1
                      
                      //if (b0 <> 0) then
                      //   MsgBox "error in last byte of sprite #" + Str(filecount)
                      //end
                      
                      // b0 must be &h00
                    wend
                  end
                end
                
                // **** new in v2.7.2
                if (trashPixelCount > 0) then
                  if (Len(trashPixelList) > 0) then
                    trashPixelList = trashPixelList + ", "
                  end
                  trashPixelList = trashPixelList + "sprite #" + Str(FileCount) + " has " + Str(trashPixelCount) + " pixels"
                end
                
                // **** new in v2.7.3
                if (whiteColorPixelCount > 0) then
                  if (Len(whiteColorPixelList) > 0) then
                    whiteColorPixelList = whiteColorPixelList + ", "
                  end
                  whiteColorPixelList = whiteColorPixelList + "sprite #" + Str(FileCount) + " has " + Str(whiteColorPixelCount) + " transparent pixels"
                end
                
                
                // done for this entry
                OutFile.Close
                if IsSoldierFile and (MaskOutFile <> NIL) then
                  MaskOutFile.Close
                end
              end
              
              // skip padding additional empty bytes
              // myEntryBytesRead = myEntrySize should be identical
              GoToPosition = GoToPosition + myEntrySize + 12    // **** new v2.6: necessary for buggy CC3-Terrain file
              InFile.Position = GoToPosition                                 // **** new v2.6: necessary for buggy CC3-Terrain file
              
            next
          end
          
          ProgressBarExtract.Visible = FALSE
          
          // now reading and extracting the appendix + appendix-report-file
          // create output file
          OutName = OutPath + "Appendix.bin"
          f2 = GetFolderItem(OutName)
          OutName = OutPath + "AppendixReport.xls"
          f3 = GetFolderItem(Outname)
          
          if (f2 <> NIL) and (f3 <> NIL) then
            #if TargetWin32
              OutFile = f2.CreateBinaryFile("")
              ReportFile = f3.CreateBinaryFile("")
            #else
              OutFile = f2.CreateBinaryFile("special/CC2Spriter binary file")
              ReportFile = f3.CreateBinaryFile("application/vnd.ms-excel")
            #endif
            OutFile.LittleEndian = InFile.LittleEndian     // take the same byte order like input file
            ReportFile.LittleEndian = TRUE                     // because it is a PC-like MS-Excel file
            CR = Chr(13)
            TAB = Chr(9)
            
            ReportFile.Write("File: " + f1.Name + TAB + TAB + TAB + TAB + "version-ID: " + Hex(myVersionID) + "h" + CR)
            ReportFile.Write("Footer-Report" + CR)
            
            count = 0 // used as sequence counter
            while not InFile.EOF
              b0 = InFile.ReadShort
              OutFile.WriteShort( b0 )
              
              // read sequence-section header
              select case b0
              case &h03EA
                ReportFile.Write(CR + "03EAh-Sequences" + CR)
                ReportFile.Write("Sequence Header" + TAB + TAB + TAB + "Sprite List" + CR)
                ReportFile.Write("No" + TAB + "Sprites" + TAB + "Indicator" + TAB + "#0" + TAB + "#1" + TAB + "#2" + TAB + "#3" + TAB + "#4" + TAB + "#5" + TAB + "#6" + TAB + "#7" + TAB + "#8" + TAB + "#9" + TAB + "#10" + TAB + "#11" + TAB + "#12" + TAB + "#13" + TAB + "#14" + TAB + "#15" + TAB + "#16" + TAB + "#17" + TAB + "#18" + TAB + "#19" + TAB + "#20" + TAB + "#21" + CR)
                count = -1
                sequenceindicator = b0
              case &h03EB
                ReportFile.Write(CR + "03EBh-Sequences" + CR)
                ReportFile.Write("Sequence Header" + TAB + TAB + TAB + "Sprite List" + CR)
                ReportFile.Write("No" + TAB + "Sprites" + TAB + "Indicator" + TAB + "#0" + TAB + "#1" + TAB + "#2" + TAB + "#3" + TAB + "#4" + TAB + "#5" + TAB + "#6" + TAB + "#7" + TAB + "#8" + TAB + "#9" + TAB + "#10" + TAB + "#11" + TAB + "#12" + TAB + "#13" + TAB + "#14" + TAB + "#15" + TAB + "#16" + TAB + "#17" + TAB + "#18" + TAB + "#19" + TAB + "#20" + TAB + "#21" + CR)
                count = -1
                sequenceindicator = b0
              else
                count = count + 1
                spritenumbers = b0
                // style_indicator
                b0 = InFile.ReadShort
                OutFile.WriteShort( b0 )
                ReportFile.Write(Str(count) + TAB + Str(spritenumbers) + TAB + Hex(b0) +"h")
                // Unknown_1
                b0 = InFile.ReadShort
                OutFile.WriteShort( b0 )
                if (sequenceindicator = &h03EA) then // has Unknown_2
                  b0 = InFile.ReadShort
                  OutFile.WriteShort( b0 )
                end
                // number list
                for i = 0 to (spritenumbers - 1)
                  b0 = InFile.ReadShort
                  OutFile.WriteShort( b0 )
                  ReportFile.Write(TAB + Str(b0))
                next
                ReportFile.Write(CR)
              end select
              
            wend
            
            OutFile.Close
          else
            MsgBox "Appendix file could not created"
          end
          
          // now write the VersionID.bin file if necessary
          if (myVersionId <> 1) then
            OutName = OutPath + "VersionID.bin"
            f2 = GetFolderItem(OutName)
            if (f2 <> NIL) then
              #if TargetWin32
                OutFile = f2.CreateBinaryFile("")
              #else
                OutFile = f2.CreateBinaryFile("special/CC2Spriter binary file")
              #endif
              OutFile.LittleEndian = InFile.LittleEndian     // take the same byte order like input file
              
              OutFile.WriteLong(myVersionId)
              OutFile.Close
            else
              MsgBox "VersionID file could not created"
            end
          end
          
          // **** new in v2.7.2: bug report
          if (Len(trashPixelList) > 0) then
            MsgBox "Found: " + trashPixelList + " too much. These pixels were ignored."
          end
          
          // **** new in v2.7.3: bug report
          if (Len(whiteColorPixelList) > 0) then
            MsgBox "Found: " + whiteColorPixelList + " coded as color pixels, which were written as transparent pixels." 
          end
          
        else
          MsgBox "empty file: " + f1.Name
        end
        InFile.Close
      end
      
    end
    
  end
  
End Sub

WindowMain.AnalyzeSpriteFile:
Sub AnalyzeSpriteFile()
  dim InFile As BinaryStream
  dim dlg1 As OpenDialog
  dim f1 As FolderItem
  dim count, i, j As Integer
  dim b0, b1 As Integer
  
  dim FormatStringCC2 As String
  dim FormatStringCC4 As String
  dim FormatStringAlph As String
  dim FormatStringTilesMac As String
  dim FormatStringTilesPC As String
  dim CRchar As String
  dim AppendixBytes As Integer     // how many trailing bytes added at end of last entry (Terrain)
  
  // header description of Sprite-File
  dim myFormatId As String
  dim myVersionId As Integer
  dim myDirectoryHeader As Integer    // must be 1000
  dim myNumberOfEntries As Integer   // for sequence 1001
  dim myNumberOfStaticAnim As Integer // for sequence 1002
  dim myNumberOfDirectionAnim As Integer // for sequence 1003
  dim myColorDepth As Integer // or number of directions ??
  dim mySpriteTableHeader As Integer   // must be 1001
  dim CC1fileFound As Boolean
  dim DoItAgain As Boolean
  dim myStartingFilePos As Integer
  dim ZeroByteFound As Boolean
  
  // header description of a single entry
  dim myWidth As Integer    // in pixel
  dim myHeight As Integer
  dim myHotspotX As Integer
  dim myHotspotY As Integer
  dim myOffset As Integer          // for ALPH (TerrainA.stm) files only
  dim myEntrySize As Integer      // counted in bytes
  dim myLines(60000) As Integer  // line offsets
  
  dim myEntryBytesRead As Integer      // counted in bytes
  dim myEntryBytesLineTable As Integer      // counted in bytes
  
  dim mySpecialChars(10000) As Integer   // the list of special chars for line description
  dim mySpecialOccurence(10000) As Integer // first occurence of this char (entry)
  dim mySpecialAmount(10000) As Integer   // the byte following the special char
  dim mySpecialCount As Integer             // how many special chars found
  dim mySpecialNew As Boolean               // if this char is new to our list
  dim myOversizedConditionRaised As String   // added v2.9.4  in 2010
  dim myOversizedLargestDim As Integer
  dim myOversizedLargestWidth As Integer
  dim myOversizedLargestHeight As Integer
  
  dim dummy As Integer
  
  FormatStringCC2 = "SPRI"
  FormatStringCC4 = "IRPS"
  FormatStringAlph = "ALPH"
  FormatStringTilesMac = "TILE"
  FormatStringTilesPC = "ELIT"
  
  dlg1 = New OpenDialog
  dlg1.Title = "Select a CC2-Sprite-File for Analyzing"
  dlg1.ActionButtonCaption = "Select"
  dlg1.PromptText = "select a sprite-file to be analyzed."
  dlg1.Filter = "any file"
  f1 = dlg1.ShowModal
  
  if (f1 <> NIL) then
    
    InFile = f1.OpenAsBinaryFile(FALSE)
    if (InFile <> NIL) then
      if (not InFile.eof) then
        InFile.LittleEndian = FALSE   REM essential, its a Mac-born file
        REM first read the header (20 bytes)
        
        myFormatId = InFile.Read(4)     REM four bytes, should be "SPRI" or "IRPS"
        if (Uppercase(myFormatId) <> Uppercase(FormatStringCC2)) and (Uppercase(myFormatId) <> Uppercase(FormatStringCC4)) and (Uppercase(myFormatId) <> Uppercase(FormatStringAlph)) then
          MsgBox "file format may be wrong, header found: " + myFormatId
        else
          myFormatId = Uppercase(myFormatId)
        end
        if (myFormatId = FormatStringCC2) or (myFormatID = FormatStringTilesMac) then
          InFile.LittleEndian = FALSE   REM essential, its a Mac-born file
        elseif (myFormatId = FormatStringCC4) or (myFormatID = FormatStringTilesPC) then
          InFile.LittleEndian = TRUE   REM essential, its a PC-born file
        elseif (myFormatId = FormatStringAlph) then
          InFile.LittleEndian = TRUE   REM essential, its a PC-born file
        else
          InFile.LittleEndian = TRUE   REM essential, its a PC-born file
        end
        
        if (myFormatId = FormatStringCC2) or (myFormatId = FormatStringCC4) then
          if not InFile.eof then
            myVersionId = InFile.ReadLong     REM four bytes
          end
          if not InFile.eof then
            myDirectoryHeader = InFile.ReadShort   REM two bytes
          end
          if not InFile.eof then
            myNumberOfEntries = InFile.ReadShort    REM two bytes
          end
          if not InFile.eof then
            myNumberOfStaticAnim = InFile.ReadShort   REM two bytes
          end
          if not InFile.eof then
            myNumberOfDirectionAnim = InFile.ReadShort   REM two bytes
          end
          if not InFile.eof then
            myColorDepth = InFile.ReadShort   REM two bytes
          end
          if not InFile.eof then
            mySpriteTableHeader = InFile.ReadShort   REM two bytes
          end
        elseif (myFormatId = FormatStringAlph) then
          if not InFile.eof then
            myVersionId = InFile.ReadLong     REM four bytes
          end
          if not InFile.eof then
            myNumberOfEntries = InFile.ReadLong    REM four bytes
          end
        elseif (myFormatId = FormatStringTilesMac) then
          if not InFile.eof then
            myVersionId = InFile.ReadShort     REM two bytes   
          end
          if not InFile.eof then
            dummy = InFile.ReadShort     REM two bytes   
          end
          if not InFile.eof then
            myNumberOfEntries = InFile.ReadLong    REM four bytes
          end
        elseif (myFormatId = FormatStringTilesPC) then
          if not InFile.eof then
            dummy = InFile.ReadShort     REM two bytes   
          end
          if not InFile.eof then
            myVersionId = InFile.ReadShort     REM two bytes   
          end
          if not InFile.eof then
            myNumberOfEntries = InFile.ReadLong    REM four bytes
          end
        else
          if not InFile.eof then
            myVersionId = InFile.ReadLong     REM four bytes
          end
        end
        
        CC1fileFound = FALSE
        mySpecialCount = 0
        AppendixBytes = 0
        myOversizedConditionRaised = ""
        myOversizedLargestDim = 0
        myOversizedLargestHeight = 0
        myOversizedLargestWidth = 0
        
        if (myFormatId = FormatStringCC2) then
          if not InFile.eof then
            // ListBoxAnalyze.DeleteAllRows
            ProgressBarAnalyze.Visible = TRUE
            ProgressBarAnalyze.Value = 0
            ProgressBarAnalyze.Maximum = myNumberOfEntries
            
            for count = 1 to myNumberOfEntries
              ProgressBarAnalyze.Value = count
              ProgressBarAnalyze.Refresh
              // read each entry
              // first: the header: 12 bytes
              if not InFile.eof then
                myWidth = InFile.ReadShort   REM two bytes
              end
              if not InFile.eof then
                myHeight = InFile.ReadShort   REM two bytes
              end
              if not InFile.eof then
                myHotSpotX = InFile.ReadShort   REM two bytes
              end
              if not InFile.eof then
                myHotSpotY = InFile.ReadShort   REM two bytes
              end
              if not InFile.eof then
                myEntrySize = InFile.ReadLong   REM four bytes
              end
              
              if (myWidth * myHeight > myOversizedLargestDim) then
                myOversizedLargestDim = myWidth * myHeight
                myOversizedLargestHeight = myHeight
                myOversizedLargestWidth = myWidth
              end
              
              if (myWidth > 200) and (myHeight > 200) then
                myOversizedConditionRaised = "Sprite image too large to process: #" + Str(count) + ", " + Str(myWidth) + "x" + Str(myHeight) + ". Analyzing stopped."
                MsgBox( myOversizedConditionRaised )
                Exit
              else
                myEntryBytesRead = 0
                
                for i = 1 to myHeight   REM (myHeight * 2) bytes
                  myLines(i) = InFile.ReadShort    REM two bytes per line of the image
                  myEntryBytesRead = myEntryBytesRead + 2
                next
                myEntryBytesLineTable = myEntryBytesRead
                
                // now the datas, processing the line offset table
                myStartingFilePos = InFile.Position
                do
                  DoItAgain = FALSE
                  myEntryBytesRead = myEntryBytesLineTable
                  InFile.Position = myStartingFilePos
                  for i = 1 to myHeight
                    if (myEntryBytesRead > myEntrySize) then  // new in v2.8.2
                      // more read than allowed, must be a CC1 sprite file ?
                      CC1fileFound = TRUE
                      DoItAgain = TRUE
                      mySpecialCount = 0
                    elseif (BitWiseAnd(myLines(i), &hFFFF) = &hFFFF) or (myLines(i) = -1) then  // complete line totally blank = white = transparent
                      // perform nothing
                    else  REM line contains pixels
                      do
                        b0 = AscB( InFile.Read(1) )
                        myEntryBytesRead = myEntryBytesRead + 1
                        
                        mySpecialNew = TRUE
                        for j = 1 to mySpecialCount
                          mySpecialNew = (mySpecialChars(j) <> b0) and mySpecialNew and (mySpecialCount < 300)
                        next
                        if mySpecialNew then
                          mySpecialCount = mySpecialCount + 1
                          mySpecialChars(mySpecialCount) = b0
                          mySpecialOccurence(mySpecialCount) = count
                        end
                        
                        select case b0
                          
                        case &hFF     // color pixel is coming
                          b1 = AscB( InFile.Read(1) )
                          myEntryBytesRead = myEntryBytesRead + 1
                          if mySpecialNew then
                            mySpecialAmount(mySpecialCount) = b1
                          end
                          // number of pixels is stored in b1
                          for j = 1 to b1
                            if CC1FileFound then
                              dummy = InFile.ReadByte
                              myEntryBytesRead = myEntryBytesRead + 1
                            else
                              dummy = InFile.ReadShort
                              myEntryBytesRead = myEntryBytesRead + 2
                            end
                          next
                          
                        case &hED      // line end specifier - fill the rest of the line with white pixels
                          //perform nothing
                          if mySpecialNew then
                            mySpecialAmount(mySpecialCount) = 0
                          end
                          
                        else
                          if (b0 >= &hC0) and (b0 <= &hC9) then   // soldier pixel is coming
                            b1 = AscB( InFile.Read(1) )
                            myEntryBytesRead = myEntryBytesRead + 1
                            if mySpecialNew then
                              mySpecialAmount(mySpecialCount) = b1
                            end
                            // number of pixels is stored in b1
                            for j = 1 to b1
                              if CC1FileFound then
                                dummy = InFile.ReadByte
                                myEntryBytesRead = myEntryBytesRead + 1
                              else
                                dummy = InFile.ReadShort
                                myEntryBytesRead = myEntryBytesRead + 2
                              end
                            next
                          else
                            b1 = AscB( InFile.Read(1) )
                            myEntryBytesRead = myEntryBytesRead + 1
                            if mySpecialNew then
                              mySpecialAmount(mySpecialCount) = b1
                            end
                            // read this amount of special pixels
                          end
                          
                        end select
                      loop until (b0 = &hED)
                    end
                  next // line
                loop until not DoItAgain
                
              end
              // done for this entry
            next
            
            // check if there are trailing bytes present
            // AppendixBytes = 0
            // while not InFile.EOF
            // dummy = InFile.ReadByte
            // AppendixBytes = AppendixBytes + 1
            // wend
            AppendixBytes = InFile.Length - InFile.Position
            
          else
            MsgBox "unexpected end of file after header"
          end
          
        elseif (myFormatId = FormatStringCC4) then
          // its a CC3-RtB file
          if not InFile.eof then
            // ListBoxAnalyze.DeleteAllRows
            ProgressBarAnalyze.Visible = TRUE
            ProgressBarAnalyze.Value = 0
            ProgressBarAnalyze.Maximum = myNumberOfEntries
            
            for count = 1 to myNumberOfEntries
              ProgressBarAnalyze.Value = count
              ProgressBarAnalyze.Refresh
              // read each entry
              // first: the header: 12 bytes
              if not InFile.eof then
                myWidth = InFile.ReadShort   REM two bytes
              end
              if not InFile.eof then
                myHeight = InFile.ReadShort   REM two bytes
              end
              if not InFile.eof then
                myHotSpotX = InFile.ReadShort   REM two bytes
              end
              if not InFile.eof then
                myHotSpotY = InFile.ReadShort   REM two bytes
              end
              if not InFile.eof then
                myEntrySize = InFile.ReadLong   REM four bytes
              end
              
              if (myWidth * myHeight > myOversizedLargestDim) then
                myOversizedLargestDim = myWidth * myHeight
                myOversizedLargestHeight = myHeight
                myOversizedLargestWidth = myWidth
              end
              
              if (myWidth > 200) and (myHeight > 200) then
                myOversizedConditionRaised = "Sprite image too large to process: #" + Str(count) + ", " + Str(myWidth) + "x" + Str(myHeight) + ". Analyzing stopped."
                MsgBox( myOversizedConditionRaised )
                Exit
              else
                myEntryBytesRead = 0
                
                // second: line offset table
                for i = 1 to myHeight   REM (myHeight * 2) bytes
                  myLines(i) = InFile.ReadShort    REM two bytes per line of the image
                  myEntryBytesRead = myEntryBytesRead + 2
                next
                
                // third: reading the lines
                myStartingFilePos = InFile.Position
                do
                  DoItAgain = FALSE
                  myEntryBytesRead = myEntryBytesLineTable
                  InFile.Position = myStartingFilePos
                  for i = 1 to myHeight
                    if (myEntryBytesRead > myEntrySize) then  // new in v2.8.4
                      // more read than allowed, must be a CC1 sprite file ?
                      CC1fileFound = TRUE
                      DoItAgain = TRUE
                      mySpecialCount = 0
                    elseif (BitWiseAnd(myLines(i), &hFFFF) = &hFFFF) or (myLines(i) = -1) then  REM complete line totally blank = white = transparent
                      // perform nothing
                      // used in Soldier/SoldierB-files, not used in Terrain files
                    else  REM line contains pixels
                      do
                        b0 = AscB( InFile.Read(1) )
                        myEntryBytesRead = myEntryBytesRead + 1
                        
                        mySpecialNew = TRUE
                        for j = 1 to mySpecialCount
                          mySpecialNew = (mySpecialChars(j) <> b0) and mySpecialNew and (mySpecialCount < 300)
                        next
                        if mySpecialNew then
                          mySpecialCount = mySpecialCount + 1
                          mySpecialChars(mySpecialCount) = b0
                          mySpecialOccurence(mySpecialCount) = count
                        end
                        
                        select case b0
                          
                        case &hFF     // color pixel is coming
                          b1 = AscB( InFile.Read(1) )
                          myEntryBytesRead = myEntryBytesRead + 1
                          if mySpecialNew then
                            mySpecialAmount(mySpecialCount) = b1
                          end
                          // number of pixels is stored in b1
                          for j = 1 to b1
                            if CC1fileFound then
                              dummy = InFile.ReadByte
                              myEntryBytesRead = myEntryBytesRead + 1
                            else
                              dummy = InFile.ReadShort
                              myEntryBytesRead = myEntryBytesRead + 2
                            end
                          next
                          
                        case &hED      // line end specifier - fill the rest of the line with white pixels
                          //perform nothing
                          if mySpecialNew then
                            mySpecialAmount(mySpecialCount) = 0
                          end
                          
                        else
                          if (b0 >= &hC0) and (b0 <= &hC9) then   // soldier pixel is coming
                            b1 = AscB( InFile.Read(1) )
                            myEntryBytesRead = myEntryBytesRead + 1
                            if mySpecialNew then
                              mySpecialAmount(mySpecialCount) = b1
                            end
                            // number of pixels is stored in b1
                            for j = 1 to b1
                              if CC1fileFound then
                                dummy = InFile.ReadByte
                                myEntryBytesRead = myEntryBytesRead + 1
                              else
                                dummy = InFile.ReadShort
                                myEntryBytesRead = myEntryBytesRead + 2
                              end
                            next
                          else
                            b1 = AscB( InFile.Read(1) )
                            myEntryBytesRead = myEntryBytesRead + 1
                            if mySpecialNew then
                              mySpecialAmount(mySpecialCount) = b1
                            end
                            // read this amount of special pixels
                          end
                          
                        end select
                      loop until (b0 = &hED)
                    end
                  next // line
                  
                  // forth: this is different to CC2: read the tailing byte with value 00h
                  // trailing byte only in Terrain files, not in Soldier/SoldierB files
                  ZeroByteFound = TRUE  // new since v2.9
                  while (myEntryBytesRead < myEntrySize) and (not CC1fileFound) and ZeroByteFound
                    b0 = AscB( InFile.Read(1) )
                    ZeroByteFound = (b0 = 0)  // new since v2.9
                    myEntryBytesRead = myEntryBytesRead + 1
                  wend
                  if not ZeroByteFound then  // new since v2.9
                    // CC4/5 Soldier/SoldierB file ?
                    InFile.Position = InFile.Position - 1  // new since v2.9
                    myEntryBytesRead = myEntryBytesRead - 1  // new since v2.9
                  end
                  // b0 must be &h00
                  
                loop until not DoItAgain
              end
            next
            
            // check if there are trailing bytes present
            // AppendixBytes = 0
            // while not InFile.EOF
            // dummy = InFile.ReadByte
            // AppendixBytes = AppendixBytes + 1
            // wend
            AppendixBytes = InFile.Length - InFile.Position
            
          else
            MsgBox "unexpected end of file after header"
          end
          
        elseif (myFormatId = FormatStringAlph) then
          
          if not InFile.eof then
            // ListBoxAnalyze.DeleteAllRows
            ProgressBarAnalyze.Visible = TRUE
            ProgressBarAnalyze.Value = 0
            ProgressBarAnalyze.Maximum = myNumberOfEntries
            
            myOffset = 0
            
            for count = 1 to myNumberOfEntries
              ProgressBarAnalyze.Value = count
              ProgressBarAnalyze.Refresh
              // read each entry of the directory (20 bytes per entry)
              if not InFile.eof then
                myHotSpotX = InFile.ReadLong   REM four bytes
              end
              if not InFile.eof then
                myHotSpotY = InFile.ReadLong   REM four bytes
              end
              if not InFile.eof then
                myWidth = InFile.ReadLong   REM four bytes
              end
              if not InFile.eof then
                myHeight = InFile.ReadLong   REM four bytes
              end
              if not InFile.eof then
                myOffset = InFile.ReadLong   REM four bytes
              end
            next
            
            InFile.Position = myOffset + (myWidth * myHeight * 4)
            // check if there are trailing bytes present
            // AppendixBytes = 0
            // while not InFile.EOF
            // dummy = InFile.ReadByte
            // AppendixBytes = AppendixBytes + 1
            // wend
            AppendixBytes = InFile.Length - InFile.Position
            
          else
            MsgBox "unexpected end of file after header"
          end
          
        end
        
        ProgressBarAnalyze.Visible = FALSE
        // now report
        #if TargetWin32
          CRchar = Chr(13) + Chr(10)
        #else
          CRchar = Chr(13)
        #endif
        ListBoxAnalyze.AddRow("File: ")
        ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = f1.DisplayName
        ListBoxAnalyze.AddRow("Format-ID: ")
        ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = myFormatId
        if (myFormatId = FormatStringCC2) then
          if CC1fileFound then
            ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) + "       ...CC1 format ID!"
          else
            ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) + "       ...CC2/CC3 format ID!"
          end
        elseif (myFormatID = FormatStringCC4) then
          if CC1fileFound then
            ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) + "       ...CC1 format ID!"
          else
            ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) + "       ...CC4-RtB format ID!"
          end
        elseif (myFormatID = FormatStringAlph) then
          ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) + "       ...CC4-RtB format ID (*.stm file)!"
        elseif (myFormatId = FormatStringTilesMac) then
          ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) + "       ...CC1 format ID (MAC version file)!"
        elseif (myFormatId = FormatStringTilesPC) then
          ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) + "       ...CC1 format ID (PC version file)!"
        else 
          ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) + "       ...invalid format ID!"
        end
        if (myFormatId = FormatStringAlph) then
          // nothing
        elseif (myFormatId = FormatStringTilesMac) then
          ListBoxAnalyze.AddRow("Header: ")
          ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = "CC1 (MAC version) file type identified: 'Terrain Tiles', no sprite file!"
        elseif (myFormatId = FormatStringTilesPC) then
          ListBoxAnalyze.AddRow("Header: ")
          ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = "CC1 (PC version) file type identified: 'TILES', no sprite file!"
        elseif (myDirectoryHeader = 1000) and (mySpriteTableHeader = 1001) then
          ListBoxAnalyze.AddRow("Header: ")
          if (myFormatId = FormatStringCC2) then
            if CC1fileFound then
              ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = "CC1 (MAC version) file type identified: " + IdentifyCC1SpriteHeader(myNumberOfStaticAnim, myNumberOfDirectionAnim, myNumberOfEntries)
            else
              ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = "CC2/CC3 file type identified: " + IdentifySpriteHeader(myNumberOfStaticAnim, myNumberOfDirectionAnim, myNumberOfEntries, TRUE)
            end
          elseif (myFormatId = FormatStringCC4) then
            if CC1fileFound then
              ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = "CC1 (PC version) file type identified: " + IdentifyCC1SpriteHeader(myNumberOfStaticAnim, myNumberOfDirectionAnim, myNumberOfEntries)
            else
              ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = "CC4/CC5 file type identified: " + IdentifySpriteHeader(myNumberOfStaticAnim, myNumberOfDirectionAnim, myNumberOfEntries, FALSE)
            end
          end
        else
          ListBoxAnalyze.AddRow("Header: ")
          ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = "probably no CC2-Sprite-file at all... wrong header"
        end
        
        ListBoxAnalyze.AddRow("Version-ID: ")
        if (myFormatId = FormatStringCC2) or (myFormatId = FormatStringCC4) then
          if (IdentifySpriteHeader(myNumberOfStaticAnim, myNumberOfDirectionAnim, myNumberOfEntries, FALSE) = "CC4/RtB-*.spr") then
            ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = Hex(myVersionId) + "h            (individual)"
          else
            ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = Str(myVersionId) + "            (should be 1)"
          end
        elseif (myFormatId = FormatStringAlph) then
          ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = Str(myVersionId) + "            (should be 2)"
        elseif (myFormatId = FormatStringTilesMac) or (myFormatId = FormatStringTilesPC) then
          ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = Str(myVersionId) + "            (should be 1)"
        end
        
        if (myFormatId = FormatStringCC2) or (myFormatId = FormatStringCC4) then
          ListBoxAnalyze.AddRow("Directory Header: ")
          ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = Str(myDirectoryHeader) +  "     (should be 1000)" 
        end
        
        if (myFormatId = FormatStringTilesMac) or (myFormatId = FormatStringTilesPC) then
          ListBoxAnalyze.AddRow("Tiles: ")
        else
          ListBoxAnalyze.AddRow("Sprites: ")
        end
        ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = Str(myNumberOfEntries)
        if (myOversizedLargestDim > 0) then
          ListBoxAnalyze.AddRow("Largest sprite: ")
          ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = Str(myOversizedLargestWidth) + "x" + Str(myOversizedLargestHeight) + " pixels"
        end
        
        if (myFormatId = FormatStringCC2) or (myFormatId = FormatStringCC4) then
          ListBoxAnalyze.AddRow("Static Animations: ")
          ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = Str(myNumberOfStaticAnim)
          ListBoxAnalyze.AddRow("Direction-based Animations:")
          ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = Str(myNumberOfDirectionAnim)
          
          ListBoxAnalyze.AddRow("Color-Depth ?: ")
          ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = Str(myColorDepth)
          if CC1fileFound then
            if (myColorDepth = GetCorrectCC1ColorDepth(myNumberOfStaticAnim, myNumberOfDirectionAnim)) then
              ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) + "        ...CC1-conform"
            else
              ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) + "        ...probably wrong"
            end
          else
            if (myColorDepth = GetCorrectColorDepth(myNumberOfStaticAnim, myNumberOfDirectionAnim, (myFormatId = FormatStringCC2))) then
              ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) + "        ...CC-conform"
            else
              ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) + "        ...probably wrong"
            end
          end
          
          ListBoxAnalyze.AddRow("Sprite-Table Header: ")
          ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = Str(mySpriteTableHeader) + "    (should be 1001)" 
        end
        
        if (myFormatId = FormatStringTilesMac) or (myFormatId = FormatStringTilesPC) then
        else
          ListBoxAnalyze.AddRow("Trailing bytes after last entry:")
          if (myOversizedConditionRaised <> "") then
            ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = "         ...not analyzed"
          elseif (AppendixBytes > 0) then
            if (myFormatId = FormatStringAlph) then
              ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = Str(AppendixBytes) + "         ...error in file"
            else
              ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = Str(AppendixBytes)
              if CC1fileFound then
                if (GetOriginalCC1AppendixSize(myNumberOfStaticAnim, myNumberOfDirectionAnim) = AppendixBytes) then
                  ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) + "    ...CC1-conform"
                else
                  ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) + "    ...modified number of bytes"
                end
              else
                if (GetOriginalAppendixSize(myNumberOfStaticAnim, myNumberOfDirectionAnim, myNumberOfEntries) = AppendixBytes) then
                  ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) + "    ...CC-conform"
                else
                  ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) + "    ...modified number of bytes"
                end
              end
            end
          else
            if (myFormatId = FormatStringAlph) then
              ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = "none          ...CC conform"
            else
              ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = "none!         ...error in file"
            end
          end
        end
        
        if (myFormatId = FormatStringCC2) or (myFormatId = FormatStringCC4) then
          ListBoxAnalyze.AddRow("Pixel line description chars ")
          ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = "used: "
          for i = 1 to mySpecialCount
            ListBoxAnalyze.AddRow("")
            if (mySpecialChars(i) <= 15) then
              ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) + "0"
            end
            ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) + Hex(mySpecialChars(i)) + "h,   1st occur. in entry #" + Str(mySpecialOccurence(i))
            if (mySpecialChars(i) <> &hED) then
              if (mySpecialChars(i) <= 15) then
                ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) + "   (0"
              else
                ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) + "   ("
              end
              ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) + Hex(mySpecialChars(i))
              if (mySpecialAmount(i) <= 15) then
                ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) + "0"
              end
              ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) = ListBoxAnalyze.Cell(ListBoxAnalyze.ListCount - 1,1) + Hex(mySpecialAmount(i)) + "h)"
            end
          next
        end
        
        if (myOversizedConditionRaised <> "") then
          ListBoxAnalyze.AddRow( "Analyzing error:" )
          ListBoxAnalyze.Cell( ListBoxAnalyze.ListCount - 1, 1 ) = myOversizedConditionRaised
        end
        ListBoxAnalyze.AddRow("")
        
      else
        MsgBox "empty file: " + f1.Name
      end
      InFile.Close
      
    end
  end
  
End Sub

WindowMain.IdentifySpriteHeader:
Function IdentifySpriteHeader(myUnknown2 As Integer, myUnknown3 As Integer, myNumberOfEntries As Integer, myFormatCC2 As Boolean) As String
  dim result As String
  
  result = "unknown"
  
  if (myUnknown2 = &h004E) and (myUnknown3 = &h0001) then
    result = "Terrain"
  elseif (myUnknown2 = &h002B) and (myUnknown3 = &h0008) then
    result = "Smoke"
  elseif (myUnknown2 = &h000D) and (myUnknown3 = &h001F) then
    result = "Explode"
  elseif (myUnknown2 = &h007F) and (myUnknown3 = &h0183) then
    result = "Soldier"
  elseif (myUnknown2 = &h007F) and (myUnknown3 = &h00FA) then
    result = "SoldierB"
  elseif (myUnknown2 = &h0003) and (myUnknown3 = &h0002) then
    result = "Veh - turreted"
  elseif (myUnknown2 = &h0002) and (myUnknown3 = &h0001) then
    result = "Veh - turretless"
  elseif (myUnknown2 = &h00A5) and (myUnknown3 = &h0002) then
    result = "CC3-Terrain"
  elseif (myUnknown2 = &h0001) and (myUnknown3 = &h0001) then
    if myFormatCC2 then
      result = "CC3-*.nsd/zsd"
    else
      result = "CC4/RtB-*.spr"
    end
  elseif (myUnknown2 = &h00B0) and (myUnknown3 = &h0002) then
    result = "CC4-Terrain"
  elseif (myUnknown2 = &h00B1) and (myUnknown3 = &h0002) then
    if (myNumberOfEntries = 474) then
      result = "CC5-Terrain"
    elseif (myNumberOfEntries = 500) then
      result = "CCM-Terrain"
    end
  elseif (myUnknown2 = &h00B3) and (myUnknown3 = &h0002) then
    result = "RtB-Terrain"
  elseif (myUnknown2 = &h00F8) and (myUnknown3 = &h0002) then
    result = "CC:WaR-Terrain"
  end
  
  Return result
End Function

WindowMain.GetCorrectColorDepth:
Function GetCorrectColorDepth(myUnknown2 As Integer, myUnknown3 As Integer, myFormatCC3 As Boolean) As Integer
  dim result As Integer
  
  result = 16
  
  if (myUnknown2 = &h004E) and (myUnknown3 = &h0001) then // Terrain
    result = 16
  elseif (myUnknown2 = &h002B) and (myUnknown3 = &h0008) then // Smoke
    result = 8
  elseif (myUnknown2 = &h000D) and (myUnknown3 = &h001F) then // Explode
    result = 16
  elseif (myUnknown2 = &h007F) and (myUnknown3 = &h0183) then // Soldier
    result = 0
  elseif (myUnknown2 = &h007F) and (myUnknown3 = &h00FA) then // SoldierB
    result = 0
  elseif (myUnknown2 = &h0003) and (myUnknown3 = &h0002) then // VehB or VehS turreted
    result = 8
  elseif (myUnknown2 = &h0002) and (myUnknown3 = &h0001) then // VehB or VehS turret-less
    result = 8
  elseif (myUnknown2 = &h0001) and (myUnknown3 = &h0001) then // *.SPR file or CC3-*.nsd/zsd file
    if myFormatCC3 then
      result = 64
    else
      result = 63  // **problem**  is 64 in some cases
    end
  elseif (myUnknown2 = &h00A5) and (myUnknown3 = &h0002) then // CC3 Terrain
    result = 16
  elseif (myUnknown2 = &h00B0) and (myUnknown3 = &h0002) then // CC4 Terrain
    result = 63
  elseif (myUnknown2 = &h00B1) and (myUnknown3 = &h0002) then // CC5 & CCM Terrain
    result = 63
  elseif (myUnknown2 = &h00B3) and (myUnknown3 = &h0002) then // RtB Terrain
    result = 63
  end
  Return result
End Function

WindowMain.GetCorrectAmountStaticAnim:
Function GetCorrectAmountStaticAnim(CC2FileName As String, myNumberOfEntries As Integer) As Integer
  dim result As Integer
  
  result = 0
  if (Uppercase(CC2FileName) = "TERRAIN") then
    result =  &h004E
  elseif (Uppercase(CC2FileName) = "SMOKE") then
    result = &h002B
  elseif (Uppercase(CC2FileName) = "EXPLODE") then
    result = &h000D
  elseif (Uppercase(CC2FileName) = "SOLDIER") or (Uppercase(CC2FileName) = "CC4SOLDIER") then
    result = &h007F
  elseif (Uppercase(CC2FileName) = "SOLDIERB") or (Uppercase(CC2FileName) = "CC4SOLDIERB") then
    result = &h007F
  elseif (Uppercase(CC2FileName) = "VEHB") then
    if (myNumberOfEntries > 32) then
      result = &h0003
    else
      result = &h0002
    end
  elseif (Uppercase(CC2FileName) = "VEHS") then
    if (myNumberOfEntries > 32) then
      result = &h0003
    else
      result = &h0002
    end
  elseif (Uppercase(CC2FileName) = "SPRfile") or (Uppercase(CC2FileName) = "SPR") then
    result = &h0001
  elseif (Uppercase(CC2FileName) = "CC3NSD") or (Uppercase(CC2FileName) = "CC3ZSD") then
    result = &h0001
  elseif (Uppercase(CC2FileName) = "CC3TERRAIN") then
    result = &h00A5
  elseif (Uppercase(CC2FileName) = "CC4TERRAIN") then
    result = &h00B0
  elseif (Uppercase(CC2FileName) = "CC5TERRAIN") then
    result = &h00B1
  elseif (Uppercase(CC2FileName) = "CCMTERRAIN") then
    result = &h00B1
  elseif (Uppercase(CC2FileName) = "RTBTERRAIN") then
    result = &h00B3
  elseif (Uppercase(CC2FileName) = "CCMTTERRAIN") then
    result = &h00B1
  elseif (Uppercase(CC2FileName) = "CCWARTERRAIN") then
    result = &h00F8
  elseif (Uppercase(CC2FileName) = "CCTLDTERRAIN") then
    result = &h00F8
  elseif (Uppercase(CC2FileName) = "CCLSATERRAIN") then
    result = &h00F8
  end
  
  Return result
  
End Function

WindowMain.GetCorrectAmountDirectionAnim:
Function GetCorrectAmountDirectionAnim(CC2FileName As String, myNumberOfEntries As Integer) As Integer
  dim result As Integer
  
  result = 0
  if (Uppercase(CC2FileName) = "TERRAIN") then
    result =  &h0001
  elseif (Uppercase(CC2FileName) = "SMOKE") then
    result = &h0008
  elseif (Uppercase(CC2FileName) = "EXPLODE") then
    result = &h001F
  elseif (Uppercase(CC2FileName) = "SOLDIER") or (Uppercase(CC2FileName) = "CC4SOLDIER") then
    result = &h0183
  elseif (Uppercase(CC2FileName) = "SOLDIERB") or (Uppercase(CC2FileName) = "CC4SOLDIERB") then
    result = &h00FA
  elseif (Uppercase(CC2FileName) = "VEHB") then
    if (myNumberOfEntries > 32) then
      result = &h0002
    else
      result = &h0001
    end
  elseif (Uppercase(CC2FileName) = "VEHS") then
    if (myNumberOfEntries > 32) then
      result = &h0002
    else
      result = &h0001
    end
  elseif (Uppercase(CC2FileName) = "SPR") or (Uppercase(CC2FileName) = "SPRfile") then
    result = &h0001
  elseif (Uppercase(CC2FileName) = "CC3NSD") or (Uppercase(CC2FileName) = "CC3ZSD") then
    result = &h0001
  elseif (Uppercase(CC2FileName) = "CC3TERRAIN") then
    result = &h0002
  elseif (Uppercase(CC2FileName) = "CC4TERRAIN") then
    result = &h0002
  elseif (Uppercase(CC2FileName) = "CC5TERRAIN") then
    result = &h0002
  elseif (Uppercase(CC2FileName) = "CCMTERRAIN") then
    result = &h0002
  elseif (Uppercase(CC2FileName) = "RTBTERRAIN") then
    result = &h0002
  elseif (Uppercase(CC2FileName) = "CCMTTERRAIN") then
    result = &h0002
  elseif (Uppercase(CC2FileName) = "CCWARTERRAIN") then
    result = &h0002
  elseif (Uppercase(CC2FileName) = "CCTLDTERRAIN") then
    result = &h0002
  elseif (Uppercase(CC2FileName) = "CCLSATERRAIN") then
    result = &h0002
  end
  
  Return result
  
End Function

WindowMain.TGAToSoldierSprite:
Sub TGAToSoldierSprite(SpriteType As String)
  dim InFile, MaskFile As BinaryStream
  dim OutFile As BinaryStream
  dim dlg2 As SaveAsDialog
  dim dlg1 As SelectFolderDialog
  dim f1, f2, f3, fMask As FolderItem
  dim InPath, MaskName, MaskPath As String
  dim OutName As String
  dim DirEntries As Integer
  dim AppendixFileFound, VersionIDfileFound As Boolean
  dim IsCC4Sprite As Boolean
  dim IsSoldierSprite As Boolean
  
  dim GreatestValueRead As Integer          // out of all external TARGA files
  dim myNumberInSequence As Integer      // of this external TARGA file
  dim myNumberOfEntries As Integer        // resulting for the sprite file to be created
  dim myNumberOfStaticAnim, myNumberOfDirectionAnim, myFoundNumberOfStaticAnim, myFoundNumberOfDirectionAnim As Integer
  dim NameTable(5000) As String
  dim WidthTable(5000) As Integer
  dim HeightTable(5000) As Integer
  dim HotXTable(5000) As Integer
  dim HotYTable(5000) As Integer
  dim dummy As String
  dim i, j, k, count As Integer
  dim transparentCount As Integer
  dim coloredCount As Integer
  dim shadowedCount As Integer
  dim filledCount As Integer
  dim whiteCount As Integer
  dim PixelReadNew, PixelReadBefore As Integer
  dim BytesPerLine, OffsetStart As Integer
  dim PixelBuffer(10000) As Integer
  dim PixelBufferSize As Integer
  dim NumberOfColoredLines As Integer
  dim SpecialCounter As Integer
  dim LineBufferSize(10000) As Integer
  dim LineBuffer(10000, 10000) As Integer
  dim OffsetBuffer(10000) As Integer
  dim MaskBuffer(10000) As Integer
  dim MaskCounter, MaskIDNew, MaskIDBefore As Integer
  dim ErrorFirstLineOutOfSize As Integer
  
  // the output colors we will use
  dim ColorTransparency As Integer
  dim ColorShadow As Integer
  dim ColorFillarea As Integer
  dim Color2ndShadow As Integer
  dim ColorMask(9) As Integer
  
  // TARGA header interpreting properties
  dim TargaHeaderLength As Integer
  dim TargaHeaderId As Integer
  dim TargaColorMapType, TargaImageType As Integer
  dim TargaFirstEntry, TargaColorMapLength, TargaColorMapEntrySize As Integer
  dim TargaColorDepth As Integer
  dim TargaImageDescriptor As Integer
  dim TargaTopDown As Boolean
  dim UnknownTargaFound As Boolean
  dim UnknownTargaEntry As String
  dim UnknownTargaColDepth, UnknownTargaImgType As Integer
  
  UnknownTargaFound = FALSE
  
  // constant defining
  // FormatString = "SPRI"
  IsCC4Sprite =  (SpriteType = "CC4TERRAIN") or (SpriteType = "CC5TERRAIN") or (SpriteType = "CCMTERRAIN") or (SpriteType = "RTBTERRAIN") or (SpriteType = "CCMTTERRAIN") or (SpriteType = "SPRfile") or (SpriteType = "CC4SOLDIER") or (SpriteType = "CC4SOLDIERB") or (SpriteType = "CCWARTERRAIN") or (SpriteType = "CCTLDTERRAIN") or (SpriteType = "CCLSATERRAIN")
  IsSoldierSprite = (SpriteType = "CC4SOLDIER") or (SpriteType = "SOLDIER") or (SpriteType = "CC4SOLDIERB") or (SpriteType = "SOLDIERB")
  
  ColorTransparency = &h7FFF // as suggested by Cpl_Filth
  ColorShadow = &h4EE0          // as suggested by Cpl_Filth
  ColorFillarea = &h7D91         // new value by Mafi
  Color2ndShadow = &h7FE1             // new value by Mafi
  for i = 0 to 9
    ColorMask(i) = (i * 1500) + 5000
  next
  
  ColorTransparency = App.ColorToTGAvalue(App.gSpecialColor(0))
  ColorShadow = App.ColorToTGAvalue(App.gSpecialColor(1))
  ColorFillarea = App.ColorToTGAvalue(App.gSpecialColor(2))
  Color2ndShadow = App.ColorToTGAvalue(App.gSpecialColor(3))
  
  // start user interface
  
  dlg1 = New SelectFolderDialog
  dlg1.Title = "Select Soldier-Sprites-Folder for Input"
  dlg1.ActionButtonCaption = "Select"
  if IsCC4Sprite then
    if (SpriteType = "SPRfile") then
      dlg1.PromptText = "select a folder with the graphics for re-building new CC4/RtB '*.spr'-file"
    else
      dlg1.PromptText = "select a folder with the graphics for re-building new '" + SpriteType + "'-file"
    end
  else
    if (SpriteType = "CC3TERRAIN") then
      dlg1.PromptText = "select a folder with the graphics for re-building new CC3-Terrain-file"
    elseif (SpriteType = "CC3NSD") then
      dlg1.PromptText = "select a folder with the graphics for re-building new CC3 '*.nsd'-file"
    elseif (SpriteType = "CC3ZSD") then
      dlg1.PromptText = "select a folder with the graphics for re-building new CC3 '*.zsd'-file"
    else
      dlg1.PromptText = "select a folder with the graphics for re-building new CC2/3-'" + SpriteType + "'-file"
    end
  end
  f1 = dlg1.ShowModal
  
  if (f1 <> NIL) then
    if f1.Directory then
      InPath = f1.AbsolutePath
      DirEntries = f1.Count
      
      dlg2 = New SaveAsDialog
      dlg2.Title = "Create new File for Output"  
      dlg2.ActionButtonCaption = "Create"
      dlg2.PromptText = "enter name for the new file to re-build with " + Str(DirEntries - 2) + " entries"
      if (SpriteType = "SPRfile") then
        dlg2.SuggestedFileName = "new Shadow.spr"
      elseif (SpriteType = "CC3NSD") then
        dlg2.SuggestedFileName = "new Shadow.nsd"
      elseif (SpriteType = "CC3ZSD") then
        dlg2.SuggestedFileName = "new Shadow.zsd"
      else
        dlg2.SuggestedFileName = SpriteType + " new"
      end
      dlg2.Filter = "any file"
      f2 = dlg2.ShowModal
      
      if (f2 <> NIL) then
        // init the internal file names table
        for count = 0 to 5000
          NameTable(count) = ""
        next
        
        REM first read all filenames and files to collect header infos
        myNumberOfEntries = 0
        GreatestValueRead = -1
        UnknownTargaFound = FALSE
        for count = 1 to DirEntries
          f3 = f1.Item(count)
          if (f3 <> NIL) then
            if not f3.Directory then
              if (Len(f3.Name) >= 14) then
                if (Uppercase(Right(f3.Name, 4)) = ".TGA") and (Uppercase(Left(f3.Name, 5)) = "IMAGE") then
                  myNumberInSequence = Val(Right(Left(f3.Name, 9), 4))
                  if (myNumberInSequence >= 0) and (myNumberInSequence <= 5000) then
                    REM valid entry
                    myNumberOfEntries = myNumberOfEntries + 1
                    if (myNumberInSequence > GreatestValueRead) then
                      GreatestValueRead = myNumberInSequence
                    end
                    
                    NameTable(myNumberInSequence) = f3.AbsolutePath
                    i = Instr(f3.name,".")                // search for the first period
                    if (i = 0) or (i >= Len(f3.name)) then
                      HotXTable(myNumberInSequence) = 0
                      HotYTable(myNumberInSequence) = 0
                    else
                      i = i + 1
                      dummy = Mid(f3.name, i, 1)
                      i = i + 1
                      while (Mid(f3.name, i, 1) <> ".") and (i <= Len(f3.name))
                        dummy = dummy + Mid(f3.name, i, 1)
                        i = i + 1
                      wend
                      HotXTable(myNumberInSequence) = Val(dummy)
                      
                      i = i + 1
                      dummy = Mid(f3.name, i, 1)
                      i = i + 1
                      while (Mid(f3.name, i, 1) <> ".") and (i <= Len(f3.name))
                        dummy = dummy + Mid(f3.name, i, 1)
                        i = i + 1
                      wend
                      HotYTable(myNumberInSequence) = Val(dummy)
                    end
                    
                    InFile = f3.OpenAsBinaryFile(FALSE)
                    if (InFile <> NIL) then
                      InFile.LittleEndian = TRUE  // its a PC-like TARGA graphics file
                      
                      // check the color depth of TARGA
                      InFile.Position = 2
                      TargaImageType = InFile.ReadByte
                      InFile.Position = 16
                      TargaColorDepth = InFile.ReadByte
                      if not ((TargaImageType = 2) and ((TargaColorDepth = 16) or (TargaColorDepth = 15))) then
                        if (not UnknownTargaFound) then
                          UnknownTargaFound = TRUE
                          UnknownTargaEntry = f3.Name
                          UnknownTargaColDepth = TargaColorDepth
                          UnknownTargaImgType = TargaImageType
                        end
                      end
                      
                      // get the image dimensions
                      InFile.Position = 12
                      WidthTable(myNumberInSequence) = InFile.ReadShort
                      HeightTable(myNumberInSequence) = InFile.ReadShort
                      
                      InFile.Close
                    end
                  end
                end
              end
            end
          end
        next
        
        // abort action if there is one or more not-16-bit Image
        if UnknownTargaFound then
          MsgBox "one or more images are not in 16-bit encoded: file " + UnknownTargaEntry + " is a " + Str(UnknownTargaColDepth) + "-bit " + App.TargaImageTypeToText(UnknownTargaImgType) + ". Operation stopped."
        else
          // all input is 16-bit clean
          
          REM now write the header
          ProgressBarRebuild.Visible = TRUE
          ProgressBarRebuild.Value = 0
          ProgressBarRebuild.Maximum = GreatestValueRead
          ProgressBarRebuild.Refresh
          
          #if TargetWin32
            OutFile = f2.CreateBinaryFile("")
          #else
            if IsCC4Sprite then
              OutFile = f2.CreateBinaryFile("special/CC5sprites")
            else
              if (SpriteType = "CC3NSD") or (SpriteType = "CC3ZSD") or (SpriteType = "CC3Terrain") then
                OutFile = f2.CreateBinaryFile("special/CC3sprites")
              else
                OutFile = f2.CreateBinaryFile("special/CC2sprites")
              end
            end
          #endif
          if (OutFile = NIL) then
            MsgBox "output file cannot be created."
          else
            myNumberOfStaticAnim = GetCorrectAmountStaticAnim(SpriteType, myNumberOfEntries)
            myNumberOfDirectionAnim = GetCorrectAmountDirectionAnim(SpriteType, myNumberOfEntries)
            if IsCC4Sprite then 
              OutFile.LittleEndian = TRUE                  // must be PC like byte order
              OutFile.Write("IRPS")                            // CC4/5/6/7-Format-ID
            else
              OutFile.LittleEndian = FALSE
              OutFile.Write("SPRI")                            // CC2/CC3-Format-ID
            end
            
            // special handling for  version-ID for *.spr files
            
            f3 = GetFolderItem(InPath + "VersionID.bin")
            VersionIDfileFound = (f3 <> NIL)
            
            if VersionIDfileFound then
              InFile = f3.OpenAsBinaryFile(FALSE)
              VersionIDfileFound = (InFile <> NIL)
              if VersionIDfileFound then
                InFile.LittleEndian = FALSE  // it doesnt matter in that case because we will read each byte seperately
                
                while not InFile.EOF
                  OutFile.WriteByte( InFile.ReadByte )
                  // if we would read short or long we must determine the byte order first!
                wend
                
                InFile.Close
              end
            end
            
            if not VersionIDfileFound then 
              OutFile.WriteLong(1)                             // Version ID always 1 in CC2 / CC3
            end
            
            OutFile.WriteShort(1000)                      // Directory-Header is always 1000 in CC2
            OutFile.WriteShort(myNumberOfEntries)   // is a two byte value in CC2
            OutFile.WriteShort(myNumberOfStaticAnim)
            OutFile.WriteShort(myNumberOfDirectionAnim)
            OutFile.WriteShort(GetCorrectColorDepth( myNumberOfStaticAnim, myNumberOfDirectionAnim, not IsCC4Sprite) )
            OutFile.WriteShort(1001)                      // Sprite-Table-Header is always 1001 in CC2
            
            REM now write the entries
            
            for count = 0 to GreatestValueRead
              if (NameTable(count) <> "") then // we have a file there
                ProgressBarRebuild.Value = count
                ProgressBarRebuild.Refresh   // **** new in v2.7.3
                
                f3 = GetFolderItem(NameTable(count))
                fMask = NIL
                MaskFile = NIL
                
                // write the entry header
                OutFile.WriteShort(WidthTable(count))   // picture width
                OutFile.WriteShort(HeightTable(count))  // picture height
                OutFile.WriteShort(HotXTable(count))     // hotspot X
                OutFile.WriteShort(HotYTable(count))    // hotspot Y
                
                // read the complete file to calculate the entry
                InFile = f3.OpenAsBinaryFile(FALSE)
                if (InFile <> NIL) then
                  // check for Mask TARGA
                  MaskName = "MASK" + Right(f3.Name, Len(f3.Name) - Len("IMAGE"))
                  MaskPath = Left(f3.AbsolutePath, InStr(f3.AbsolutePath, f3.Name) - 1) + MaskName
                  fMask = GetFolderItem(MaskPath)
                  if (fMask <> NIL) then
                    MaskFile = fMask.OpenAsBinaryFile(FALSE)
                  end
                  
                  // go on reading InFile
                  InFile.LittleEndian = TRUE  // its a PC-like TARGA graphics file
                  if (MaskFile <> NIL) then
                    MaskFile.LittleEndian = TRUE
                  end
                  
                  // interpreting TARGA header
                  TargaHeaderId = InFile.ReadByte  // one single byte. if it is 0, then header length = 18, if it is 1 than header length = 19, etc
                  TargaHeaderLength = 18 + TargaHeaderId
                  
                  // look for color map
                  TargaColorMapType = InFile.ReadByte
                  TargaImageType = InFile.ReadByte
                  if (TargaColorMapType <> 0) then // a color map is included
                    TargaFirstEntry = InFile.ReadShort
                    TargaColorMapLength = InFile.ReadShort
                    TargaColorMapEntrySize = InFile.ReadByte   // counted in bits
                    if (TargaColorMapEntrySize >= 9) and (TargaColorMapEntrySize <= 16) then
                      TargaColorMapEntrySize = 16  // counted in bits
                    end
                    
                    TargaHeaderLength = TargaHeaderLength + ((TargaColorMapLength * TargaColorMapEntrySize) \ 8)  // counted in bytes
                  end
                  
                  // now read the data orientation
                  InFile.Position = 16
                  if (MaskFile <> NIL) then
                    MaskFile.Position = 16
                  end
                  TargaColorDepth = InFile.ReadByte
                  TargaImageDescriptor = InFile.ReadByte
                  TargaTopDown = (BitWiseAnd(TargaImageDescriptor, 32) = 32)
                  
                  // now read the datas
                  InFile.Position = TargaHeaderLength
                  if (MaskFile <> NIL) then
                    MaskFile.Position = TargaHeaderLength
                  end
                  
                  OffsetStart = 0                     // beginning of datas of first colored pixel
                  NumberOfColoredLines = 0    // no lines with pixels yet
                  for i = 1 to HeightTable(count)  // process lines
                    // respect the TARGA orientation
                    if RadioButtonRespectTGAheader.Value then
                      if TargaTopDown then
                        InFile.Position = TargaHeaderLength + ((i - 1) * WidthTable(count) * 2)
                        if (MaskFile <> NIL) then
                          MaskFile.Position = TargaHeaderLength + ((i - 1) * WidthTable(count) * 2)
                        end
                      else
                        InFile.Position = TargaHeaderLength + ((HeightTable(count) - i) * WidthTable(count) * 2)
                        if (MaskFile <> NIL) then
                          MaskFile.Position = TargaHeaderLength + ((HeightTable(count) - i) * WidthTable(count) * 2)
                        end
                      end
                    else
                      InFile.Position = TargaHeaderLength + ((i - 1) * WidthTable(count) * 2)
                      if (MaskFile <> NIL) then
                        MaskFile.Position = TargaHeaderLength + ((i - 1) * WidthTable(count) * 2)
                      end
                    end
                    
                    LineBufferSize(i) = 0
                    PixelReadBefore = &hFFFF
                    MaskIDBefore = -1
                    PixelBufferSize = 0
                    SpecialCounter = 0
                    MaskCounter = 0
                    for j = 1 to WidthTable(count)  // process all pixels of this line
                      PixelReadNew = InFile.ReadShort
                      
                      if (((PixelReadNew - 5000) MOD 1500) = 0) then
                        MaskIDNew = ((PixelReadNew - 5000) \ 1500)
                      else
                        MaskIDNew = -1  // no valid mask color
                      end
                      
                      if ((MaskIDNew >= 0) and (MaskIDNew <= 9)) or (PixelReadNew = ColorTransparency) or (PixelReadNew = ColorShadow) or (PixelReadNew = ColorFillarea) or (PixelReadNew = Color2ndShadow) then
                        // is a special color or is a special mask color of Soldier/SoldierB
                        if (PixelReadNew <> PixelReadBefore) and (PixelReadBefore <> &hFFFF) then
                          if (PixelBufferSize > 0) then
                            // transfer all color pixels to the line buffer
                            LineBufferSize(i) = LineBufferSize(i) + 1
                            if IsCC4Sprite then
                              LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(PixelBufferSize, 8) + &hFF
                            else
                              // CC2 & CC3
                              LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(&hFF, 8) + PixelBufferSize
                            end
                            for k = 1 to PixelBufferSize
                              LineBufferSize(i) = LineBufferSize(i) + 1
                              LineBuffer(i, LineBufferSize(i)) = PixelBuffer(k)
                            next
                            PixelBufferSize = 0
                          else
                            // transfer special char and length byte to the line buffer
                            LineBufferSize(i) = LineBufferSize(i) + 1
                            select case PixelReadBefore
                            case ColorTransparency
                              if IsCC4Sprite then
                                LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(SpecialCounter, 8) + &h00
                              else
                                // CC2 & CC3
                                LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(&h00, 8) + SpecialCounter
                              end
                            case ColorShadow
                              if IsCC4Sprite then
                                LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(SpecialCounter, 8) + &hF5
                              else
                                // CC2 & CC3
                                LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(&hF5, 8) + SpecialCounter
                              end
                            case ColorFillarea
                              if IsCC4Sprite then
                                LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(SpecialCounter, 8) + &hF7
                              else
                                // CC2 & CC3
                                LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(&hF7, 8) + SpecialCounter
                              end
                            case Color2ndShadow
                              if IsCC4Sprite then
                                LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(SpecialCounter, 8) + &hF9
                              else
                                // CC2 & CC3
                                LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(&hF9, 8) + SpecialCounter
                              end
                            else
                              // mask color of Soldier/SoldierB
                              if ((MaskIDBefore >= 0) and (MaskIDBefore <= 9)) then
                                if IsCC4Sprite then
                                  LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(SpecialCounter, 8) + &hC0 + MaskIDBefore
                                else
                                  // CC2 & CC3
                                  LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(&hC0 + MaskIDBefore, 8) + SpecialCounter
                                end
                                for k = 1 to MaskCounter
                                  LineBufferSize(i) = LineBufferSize(i) + 1
                                  LineBuffer(i, LineBufferSize(i)) = MaskBuffer(k)
                                next
                                MaskCounter = 0
                              end
                            end select
                          end
                          SpecialCounter = 1 // we start with a new special color
                          if ((MaskIDNew >= 0) and (MaskIDNew <= 9)) then
                            if (MaskFile <> NIL) then
                              MaskCounter = 1
                              MaskFile.Position = InFile.Position - 2  // 2 bytes back
                              MaskBuffer(MaskCounter) = MaskFile.ReadShort
                            end
                          end
                        else
                          SpecialCounter = SpecialCounter + 1
                          if ((MaskIDNew >= 0) and (MaskIDNew <= 9)) then
                            if (MaskFile <> NIL) then
                              MaskCounter = MaskCounter + 1
                              MaskFile.Position = InFile.Position - 2
                              MaskBuffer(MaskCounter) = MaskFile.ReadShort
                            end
                          end
                        end
                      else // it is a colored Pixel
                        if (SpecialCounter > 0) then
                          // transfer special char and length byte to the line buffer
                          LineBufferSize(i) = LineBufferSize(i) + 1
                          select case PixelReadBefore
                          case ColorTransparency
                            if IsCC4Sprite then
                              LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(SpecialCounter, 8) + &h00
                            else
                              // CC2 & CC3
                              LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(&h00, 8) + SpecialCounter
                            end
                          case ColorShadow
                            if IsCC4Sprite then
                              LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(SpecialCounter, 8) + &hF5
                            else
                              // CC2 & CC3
                              LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(&hF5, 8) + SpecialCounter
                            end
                          case ColorFillarea
                            if IsCC4Sprite then
                              LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(SpecialCounter, 8) + &hF7
                            else
                              // CC2 & CC3
                              LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(&hF7, 8) + SpecialCounter
                            end
                          case Color2ndShadow
                            if IsCC4Sprite then
                              LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(SpecialCounter, 8) + &hF9
                            else
                              // CC2 & CC3
                              LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(&hF9, 8) + SpecialCounter
                            end
                          else
                            // mask color of Soldier/SoldierB
                            if ((MaskIDBefore >= 0) and (MaskIDBefore <= 9)) then
                              if IsCC4Sprite then
                                LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(SpecialCounter, 8) + &hC0 + MaskIDBefore
                              else
                                // CC2 & CC3
                                LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(&hC0 + MaskIDBefore, 8) + SpecialCounter
                              end
                              for k = 1 to MaskCounter
                                LineBufferSize(i) = LineBufferSize(i) + 1
                                LineBuffer(i, LineBufferSize(i)) = MaskBuffer(k)
                              next
                              MaskCounter = 0
                            end
                          end select
                        end
                        SpecialCounter = 0
                        PixelBufferSize = PixelBufferSize + 1
                        PixelBuffer(PixelBufferSize) = PixelReadNew
                      end
                      PixelReadBefore = PixelReadNew
                      MaskIDBefore = MaskIDNew
                    next // process all pixels of this line
                    
                    if ((SpecialCounter = WidthTable(count)) and ((PixelReadBefore = ColorTransparency) or (PixelReadBefore = &hFFFF))) and (IsSoldierSprite or not IsCC4Sprite) then
                      // entire line is transparent, no pixel datas preserved
                      OffsetBuffer(i) = &hFFFF
                    else
                      if (PixelBufferSize > 0) then
                        // transfer all color pixels to the line buffer
                        LineBufferSize(i) = LineBufferSize(i) + 1
                        if IsCC4Sprite then
                          LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(PixelBufferSize, 8) + &hFF
                        else
                          // CC2 & CC3
                          LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(&hFF, 8) + PixelBufferSize
                        end
                        for k = 1 to PixelBufferSize
                          LineBufferSize(i) = LineBufferSize(i) + 1
                          LineBuffer(i, LineBufferSize(i)) = PixelBuffer(k)
                        next
                        PixelBufferSize = 0
                      elseif (SpecialCounter > 0) then
                        select case PixelReadBefore
                        case ColorTransparency
                          if IsCC4Sprite and not IsSoldierSprite then
                            LineBufferSize(i) = LineBufferSize(i) + 1
                            LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(SpecialCounter, 8) + &h00
                          else
                            // CC2 & CC3
                            // only in CC2 and CC3 and in Soldier/SoldierB the transparency pixels remaining will be resolved by end-of-line byte
                          end
                        case ColorShadow
                          LineBufferSize(i) = LineBufferSize(i) + 1
                          if IsCC4Sprite then
                            LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(SpecialCounter, 8) + &hF5
                          else
                            // CC2 & CC3
                            LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(&hF5, 8) + SpecialCounter
                          end
                        case ColorFillarea
                          LineBufferSize(i) = LineBufferSize(i) + 1
                          if IsCC4Sprite then
                            LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(SpecialCounter, 8) + &hF7
                          else
                            // CC2 & CC3
                            LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(&hF7, 8) + SpecialCounter
                          end
                        case Color2ndShadow
                          LineBufferSize(i) = LineBufferSize(i) + 1
                          if IsCC4Sprite then
                            LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(SpecialCounter, 8) + &hF9
                          else
                            // CC2 & CC3
                            LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(&hF9, 8) + SpecialCounter
                          end
                        else
                          // mask color of Soldier/SoldierB
                          if ((MaskIDBefore >= 0) and (MaskIDBefore <= 9)) then
                            LineBufferSize(i) = LineBufferSize(i) + 1
                            if IsCC4Sprite then
                              LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(SpecialCounter, 8) + &hC0 + MaskIDBefore
                            else
                              // CC2 & CC3
                              LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(&hC0 + MaskIDBefore, 8) + SpecialCounter
                            end
                            for k = 1 to MaskCounter
                              LineBufferSize(i) = LineBufferSize(i) + 1
                              LineBuffer(i, LineBufferSize(i)) = MaskBuffer(k)
                            next
                            MaskCounter = 0
                          end
                        end select
                        // only in CC2 and CC3 and in Soldier/SoldierB the transparency pixels remaining will be resolved by end-of-line byte
                        SpecialCounter = 0
                      end
                      // the end-of-line byte will be added later
                      OffsetBuffer(i) = OffsetStart
                      OffsetStart = OffsetStart + (LineBufferSize(i) * 2) + 1
                      NumberOfColoredLines = NumberOfColoredLines + 1
                    end
                  next // process all lines
                  
                  InFile.Close
                  if (MaskFile <> NIL) then
                    MaskFile.Close
                  end
                end
                
                // now write the last entry of the header: the offset-table + data size
                if IsCC4Sprite and not IsSoldierSprite then
                  // something special: an additional zero byte after the last &hED, so the size is one byte larger than in CC2
                  OutFile.WriteLong((HeightTable(count) * 2) + OffsetStart + 1)     // size of offset-table + pixel data
                else
                  // CC2 and CC3
                  OutFile.WriteLong((HeightTable(count) * 2) + OffsetStart)     // size of offset-table + pixel data
                end
                
                // write the offset table
                ErrorFirstLineOutOfSize = -1
                for i = 1 to HeightTable(count)
                  if (OffsetBuffer(i) > &hFFFF) then
                    // new in v2.9.4: checking for images which are too big
                    OutFile.WriteShort(&hFFFF)  // size to big for SHORT, code this line as WHITE as a compromise
                    // do not set OffsetBuffer(i) = &hFFFF, this will corrupt the internal offset calculations,
                    // in other words: you must define these lines as whites, but you must write their pixels
                    // to get proper offset calculations for the next image...
                    if (ErrorFirstLineOutOfSize < 0) then
                      ErrorFirstLineOutOfSize = i
                    end
                  else
                    OutFile.WriteShort(OffsetBuffer(i))
                  end
                next
                if (ErrorFirstLineOutOfSize >= 0) then
                  MsgBox("Image #" + Str(count) + " too large (" + Str(WidthTable(count)) + "x" + Str(HeightTable(count)) + " pixels). Starting with line " + Str(ErrorFirstLineOutOfSize) + ", the image will be filled with white lines.")
                end
                
                // write the compressed pixel datas
                for i = 1 to HeightTable(count)
                  if (OffsetBuffer(i) <> &hFFFF) then // this line has datas
                    for j = 1 to LineBufferSize(i)
                      OutFile.WriteShort(LineBuffer(i, j))
                    next
                    OutFile.WriteByte(&hED)   // write end-of-line byte
                  end
                next
                if IsCC4Sprite and not IsSoldierSprite then
                  // something special: an additional zero byte after the last &hED, so the size is one byte larger than in CC2
                  OutFile.WriteByte(0)        // write end-of-entry byte = zero
                end
                // job done for this entry
                
              end // of we have a file there
            next // entry processing
            
            // now add the appendix/footer
            f3 = GetFolderItem(InPath + "Appendix.bin")
            AppendixFileFound = (f3 <> NIL)
            
            if AppendixFileFound then
              // new in v2.9.1: check the number of entries inside Appendix.bin
              AppendixFileFound = AnalyzeAppendixFile(f3, myFoundNumberOfStaticAnim, myFoundNumberOfDirectionAnim)
              
              if AppendixFileFound then
                // control the number of entries
                if (myFoundNumberOfStaticAnim <> myNumberOfStaticAnim) then
                  MsgBox("Number of Static-Animations found inside '" + f3.Name + "' is " + Str(myFoundNumberOfStaticAnim) + " (should be originally " + Str(myNumberOfStaticAnim) + "). Header will be patched accordingly.")
                  OutFile.Position = 12
                  OutFile.WriteShort(myFoundNumberOfStaticAnim)
                end
                if (myFoundNumberOfDirectionAnim <> myNumberOfDirectionAnim) then
                  MsgBox("Number of Direction-based-Animations found inside '" + f3.Name + "' is " + Str(myFoundNumberOfDirectionAnim) + " (should be originally " + Str(myNumberOfDirectionAnim) + "). Header will be patched accordingly.")
                  OutFile.Position = 14
                  OutFile.WriteShort(myFoundNumberOfDirectionAnim)
                end
              end
              
              // append Appendix.bin
              OutFile.Position = OutFile.Length
              InFile = f3.OpenAsBinaryFile(FALSE)
              AppendixFileFound = (InFile <> NIL)
              if AppendixFileFound then
                InFile.LittleEndian = FALSE  // it doesnt matter in that case because we will read each byte seperately
                
                while not InFile.EOF
                  OutFile.WriteByte( InFile.ReadByte )
                  // if we would read short or long we must determine the byte order first!
                wend
                
                InFile.Close
              end
            end
            
            if not AppendixFileFound then 
              if (SpriteType = "VehB") or (SpriteType = "VehS") then
                // generate a valid appendix from scratch
                
                if (myNumberOfEntries >= 64) then
                  // its a turreted vehicle
                  OutFile.WriteShort( &h03EA )   // header-ID
                  OutFile.WriteShort( 1 )            // number of sprites in sequence
                  OutFile.WriteShort( &h2200 )  // style indicator
                  OutFile.WriteShort( 0 )            // unknown
                  OutFile.WriteShort( 0 )            // unknown
                  OutFile.WriteShort( 0 )           // sprite-number
                  OutFile.WriteShort( 1 )            // number of sprites in sequence
                  OutFile.WriteShort( &h2200 )  // style indicator
                  OutFile.WriteShort( 0 )            // unknown
                  OutFile.WriteShort( 0 )            // unknown
                  OutFile.WriteShort( 1 )           // sprite-number
                  OutFile.WriteShort( 1 )            // number of sprites in sequence
                  OutFile.WriteShort( &h2220 )  // style indicator
                  OutFile.WriteShort( 0 )            // unknown
                  OutFile.WriteShort( 0 )            // unknown
                  OutFile.WriteShort( 0 )           // sprite-number
                  
                  OutFile.WriteShort( &h03EB )   // header-ID
                  OutFile.WriteShort( 32 )          // number of sprites in sequence
                  OutFile.WriteShort( 0 )            // unknown
                  OutFile.WriteShort( 0 )            // unknown
                  for i = 0 to 31
                    OutFile.WriteShort( i )           // sprite-number for hull
                  next
                  OutFile.WriteShort( 32 )          // number of sprites in sequence
                  OutFile.WriteShort( 0 )            // unknown
                  OutFile.WriteShort( 0 )            // unknown
                  for i = 32 to 63
                    OutFile.WriteShort( i )           // sprite-number for gun/turret
                  next
                  
                else
                  // its turretless
                  OutFile.WriteShort( &h03EA )   // header-ID
                  OutFile.WriteShort( 1 )            // number of sprites in sequence
                  OutFile.WriteShort( &h2200 )  // style indicator
                  OutFile.WriteShort( 0 )            // unknown
                  OutFile.WriteShort( 0 )            // unknown
                  OutFile.WriteShort( 0 )           // sprite-number
                  OutFile.WriteShort( 1 )            // number of sprites in sequence
                  OutFile.WriteShort( &h2220 )  // style indicator
                  OutFile.WriteShort( 0 )            // unknown
                  OutFile.WriteShort( 0 )            // unknown
                  OutFile.WriteShort( 0 )           // sprite-number
                  
                  OutFile.WriteShort( &h03EB )   // header-ID
                  OutFile.WriteShort( 32 )          // number of sprites in sequence
                  OutFile.WriteShort( 0 )            // unknown
                  OutFile.WriteShort( 0 )            // unknown
                  for i = 0 to 31
                    OutFile.WriteShort( i )           // sprite-number
                  next
                end
              elseif (SpriteType = "SPRfile") then
                // its a turreted vehicle
                OutFile.WriteShort( &h03EA )   // header-ID
                OutFile.WriteShort( 1 )            // number of sprites in sequence
                OutFile.WriteShort( &hFFF2 )  // style indicator
                OutFile.WriteShort( &hF51C )            // unknown
                OutFile.WriteShort( &h0068 )            // unknown
                OutFile.WriteShort( 0 )           // sprite-number
                
                OutFile.WriteShort( &h03EB )   // header-ID
                OutFile.WriteShort( 64 )          // number of sprites in sequence
                OutFile.WriteShort( &hFFF2 )  // style indicator
                OutFile.WriteShort( &hF51C )            // unknown
                for i = 0 to 63
                  OutFile.WriteShort( i )           // sprite-number
                next
              elseif (SpriteType = "CC3NSD") or (SpriteType = "CC3ZSD") then
                //  turreted doesnt matter ???
                OutFile.WriteShort( &h03EA )   // header-ID
                OutFile.WriteShort( 1 )            // number of sprites in sequence
                OutFile.WriteShort( &h2200 )  // style indicator
                OutFile.WriteShort( &h0000 )            // unknown
                OutFile.WriteShort( &h0000 )            // unknown
                OutFile.WriteShort( 0 )           // sprite-number
                
                OutFile.WriteShort( &h03EB )   // header-ID
                OutFile.WriteShort( 64 )          // number of sprites in sequence
                OutFile.WriteShort( &h0000 )  // style indicator
                OutFile.WriteShort( &h0000 )            // unknown
                for i = 0 to 63
                  OutFile.WriteShort( i )           // sprite-number
                next
                
              else
                MsgBox "Appendix.bin file not found for adding, file will not work in CC"
              end
            end
            
            OutFile.Close
            ProgressBarRebuild.Visible = FALSE
          end // output file was created
        end // all input files were valid 16-bit TARGAS
      end // user selected a valid output filename
    end // its a valid input directory
  end // user selected a valid input directory
  
End Sub

WindowMain.GetOriginalAppendixSize:
Function GetOriginalAppendixSize(myUnknown2 As Integer, myUnknown3 As Integer, myNumberOfEntries As Integer) As Integer
  dim result As Integer
  
  result = 16
  
  if (myUnknown2 = &h004E) and (myUnknown3 = &h0001) then // Terrain
    result = 1288
  elseif (myUnknown2 = &h002B) and (myUnknown3 = &h0008) then // Smoke
    result = 1652
  elseif (myUnknown2 = &h000D) and (myUnknown3 = &h001F) then // Explode
    result = 1492
  elseif (myUnknown2 = &h007F) and (myUnknown3 = &h0183) then // Soldier
    result = 11314
  elseif (myUnknown2 = &h007F) and (myUnknown3 = &h00FA) then // SoldierB
    result = 7528
  elseif (myUnknown2 = &h0003) and (myUnknown3 = &h0002) then // VehB or VehS turreted
    if (myNumberOfEntries = 32) then
      result = 94
    else
      result = 174
    end
  elseif (myUnknown2 = &h0002) and (myUnknown3 = &h0001) then // VehB or VehS turret-less
    if (myNumberOfEntries = 32) then
      result = 94
    else
      result = 174
    end
  elseif (myUnknown2 = &h0001) and (myUnknown3 = &h0001) then // CC4-RtB *.spr file and CC3 *.nsd/zsd files
    result = 148
  elseif (myUnknown2 = &h00A5) and (myUnknown3 = &h0002) then // CC3 Terrain
    result = 1992
  elseif (myUnknown2 = &h00B0) and (myUnknown3 = &h0002) then // CC4 Terrain
    result = 1972
  elseif (myUnknown2 = &h00B1) and (myUnknown3 = &h0002) then 
    if (myNumberOfEntries = 474) then // CC5 Terrain
      result = 1980
    elseif (myNumberOfEntries = 500) then // CCM Terrain
      result = 2004
    end
  elseif (myUnknown2 = &h00B3) and (myUnknown3 = &h0002) then // RtB Terrain
    result = 2024
  elseif (myUnknown2 = &h00F8) and (myUnknown3 = &h0002) then // CC:WaR Terrain
    result = 2714
  end
  
  Return result
End Function

WindowMain.SaveReportToFile:
Sub SaveReportToFile()
  dim dlg1 As SaveAsDialog
  dim f1 As FolderItem
  dim OutFile As BinaryStream
  dim CRchar, TABchar As String
  dim i As Integer
  
  #if TargetWin32
    CRchar = Chr(13) + Chr(10)
  #else
    CRchar = Chr(13)
  #endif
  TABchar = Chr(9)
  
  
  dlg1 = New SaveAsDialog
  dlg1.Title = "Save Report to Text-File"
  dlg1.ActionButtonCaption = "Save"
  dlg1.PromptText = "enter name for new text file"
  f1 = dlg1.ShowModal
  
  if (f1 <> NIL) then
    OutFile = f1.CreateBinaryFile("text")
    for i = 0 to (ListBoxAnalyze.ListCount - 1)
      OutFile.Write( ListBoxAnalyze.Cell(i,0) + TABchar + ListBoxAnalyze.Cell(i,1) + CRchar )
    next
    OutFile.Close
  end
End Sub

WindowMain.AlphToTGA:
Sub AlphToTGA(WithAlphaCorrection As Boolean, ExportColorDepth As Integer)
  dim InFile As BinaryStream
  dim OutFile As BinaryStream
  dim ReportFile As BinaryStream
  dim OutPath As String
  dim OutName As String
  dim dlg1 As OpenDialog
  dim dlg2 As SelectFolderDialog
  dim f1, f2, f3 As FolderItem
  dim count, i, j, filecount As Integer
  dim CR, TAB As String
  
  dim FormatStringAlph As String
  
  // header description of Sprite-File
  dim myFormatId As String
  dim myVersionId As Integer
  dim myNumberOfEntries As Integer   // for sequence 1001
  
  // directory entry of a single alpha-sprite
  dim myWidth(10000) As Integer    // in pixel
  dim myHeight(10000) As Integer
  dim myHotspotX(10000) As Integer
  dim myHotspotY(10000) As Integer
  dim myOffset(10000) As Integer  // graphics data offsets
  
  // color storing 32 bit
  dim myBlue, myGreen, myRed, myAlpha As Integer
  
  // constant defining
  FormatStringAlph = "ALPH"
  
  //start user interface
  dlg1 = New OpenDialog
  dlg1.Title = "Select a TerrainA.stm-File for Input"
  dlg1.ActionButtonCaption = "Select"
  dlg1.PromptText = "select an alpha-channel-sprite-file to be splitted into TARGA graphics files."
  dlg1.Filter = "any file"
  f1 = dlg1.ShowModal
  
  if (f1 <> NIL) then
    
    dlg2 = New SelectFolderDialog
    dlg2.Title = "Select Folder for new Files"  
    dlg2.ActionButtonCaption = "Select"
    dlg2.PromptText = "select folder to store the new files."
    dlg2.Filter = "any file"
    f2 = dlg2.ShowModal
    
    if (f2 <> NIL) then
      OutPath = f2.AbsolutePath
      #if TargetWin32
        if (Right(OutPath, 1) <> "\") then
          OutPath = OutPath + "\"
        end
      #else
        if (Right(OutPath, 1) <> ":") then
          OutPath = OutPath + ":"
        end
      #endif
      
      InFile = f1.OpenAsBinaryFile(FALSE)
      if (InFile <> NIL) then
        if (not InFile.eof) then
          InFile.LittleEndian = TRUE   REM essential, its a PC-born file
          REM first read the header (12 bytes)
          
          myFormatId = InFile.Read(4)     REM four bytes, should be "ALPH"
          if (Uppercase(myFormatId) <> Uppercase(FormatStringAlph)) then
            MsgBox "file format may be wrong, header found: " + myFormatId
          end
          
          if not InFile.eof then
            myVersionId = InFile.ReadLong     REM four bytes
          end
          if not InFile.eof then
            myNumberOfEntries = InFile.ReadLong    REM four bytes
          end
          
          if (myNumberOfEntries > 10000) then
            MsgBox "sorry, can only handle up to 10000 entries."
            myNumberOfEntries = 10000
          end
          
          if (not InFile.eof) then
            ProgressBarTerrainA.Visible = TRUE
            ProgressBarTerrainA.Value = 0
            ProgressBarTerrainA.Maximum = myNumberOfEntries
            ProgressBarTerrainA.Refresh   // **** new in v2.7.3
            
            for count = 1 to myNumberOfEntries
              ProgressBarTerrainA.Value = count
              ProgressBarTerrainA.Refresh   // **** new in v2.7.3
              // read each entry in the directory (20 bytes)
              if not InFile.eof then
                myHotSpotX(count) = InFile.ReadLong   REM four bytes
              end
              if not InFile.eof then
                myHotSpotY(count) = InFile.ReadLong   REM four bytes
              end
              if not InFile.eof then
                myWidth(count) = InFile.ReadLong   REM four bytes
              end
              if not InFile.eof then
                myHeight(count) = InFile.ReadLong   REM four bytes
              end
              if not InFile.eof then
                myOffset(count) = InFile.ReadLong   REM four bytes
              end
            next
            
            for count = 1 to myNumberOfEntries
              ProgressBarTerrainA.Value = count
              ProgressBarTerrainA.Refresh   // **** new in v2.7.3
              
              // create output filename
              if RadioButtonCountZeroA.Value then
                filecount = count - 1
              else
                filecount = count
              end
              OutName = OutPath + "Image"
              if (filecount < 10) then
                OutName = OutName + "0"
              end
              if (filecount < 100) then
                OutName = OutName + "0"
              end
              if (filecount < 1000) then
                OutName = OutName + "0"
              end
              OutName = OutName + Str(filecount) + "." + Str(myHotspotX(count)) + "." + Str(myHotspotY(count)) + ".tga"
              
              // create output file
              f2 = GetFolderItem(OutName)
              
              if (f2 <> NIL) then
                #if TargetWin32
                  OutFile = f2.CreateBinaryFile("")
                #else
                  OutFile = f2.CreateBinaryFile("image/x-targa")
                #endif
                OutFile.LittleEndian = TRUE   REM because it is a PC-like TARGA graphics file
                
                // first: the TARGA-header
                OutFile.WriteShort(0)     // no ID, no color map
                OutFile.WriteShort(2)     // Image Type: uncompressed True-Color
                OutFile.WriteLong(0)      // no color map
                OutFile.WriteLong(0)      // image origin lower left
                OutFile.WriteShort(myWidth(count))
                OutFile.WriteShort(myHeight(count))
                if (ExportColorDepth = 16) then
                  OutFile.WriteByte(16)  // we will always create 16-bit images
                  if RadioButtonTopDownA.Value then
                    OutFile.WriteByte(33)
                  else
                    OutFile.WriteByte(1)
                  end
                else
                  OutFile.WriteByte(32)  // only here we will create 32-bit images
                  //OutFile.WriteByte(8)    // as Cpl_Filth did in his ccfx.exe tool, thanks Cpl !
                  if RadioButtonTopDownA.Value then
                    OutFile.WriteByte(40)
                  else
                    OutFile.WriteByte(8)
                  end
                end
                
                // now the datas, processing the offset table
                InFile.Position = myOffset(count)
                for i = 1 to myHeight(count)
                  for j = 1 to myWidth(count)
                    myBlue = InFile.ReadByte       // input is 32-bit color graphics with 8-bit alpha channel
                    myGreen = InFile.ReadByte
                    myRed = InFile.ReadByte
                    myAlpha = InFile.ReadByte
                    
                    // we must use Cpl_Filths algorithm of making 32-bit TARGAS
                    // Cpl_Filth's color correction
                    if ( ( 8 * myBlue - 1 ) > 0 ) then
                      myBlue = (8 * myBlue) -1
                    end
                    if ( ( 8 * myGreen - 1 ) > 0 ) then
                      myGreen = (8 * myGreen) -1
                    end
                    if ( ( 8 * myRed - 1 ) > 0 ) then
                      myRed = (8 * myRed) -1
                    end
                    if ( myAlpha <> 0 ) then
                      myAlpha = (8 * myAlpha) -1
                    end
                    
                    if (ExportColorDepth = 16) then
                      if not WithAlphaCorrection then
                        myAlpha = 0
                      end
                      OutFile.WriteShort( App.ColorToTGAvalue( RGB(myBlue + myAlpha, myGreen + myAlpha, myRed + myAlpha) ) )
                    else
                      OutFile.WriteByte(myRed)
                      OutFile.WriteByte(myGreen)
                      OutFile.WriteByte(myBlue)
                      OutFile.WriteByte(myAlpha)
                    end
                  next //pixel
                next //line
                
                // done for this entry
                OutFile.Close
              end // TARGA was written
              
            next
          end
          
          ProgressBarTerrainA.Visible = FALSE
        else
          MsgBox "empty file: " + f1.Name
        end
        InFile.Close
        
      end
      
    end
  end
  
End Sub

WindowMain.TGAToAlph:
Sub TGAToAlph()
  dim InFile As BinaryStream
  dim OutFile As BinaryStream
  dim dlg2 As SaveAsDialog
  dim dlg1 As SelectFolderDialog
  dim f1, f2, f3 As FolderItem
  dim InPath As String
  dim OutName As String
  dim DirEntries As Integer
  dim AppendixFileFound As Boolean
  
  dim GreatestValueRead As Integer          // out of all external TARGA files
  dim myNumberInSequence As Integer      // of this external TARGA file
  dim myNumberOfEntries As Integer        // resulting for the sprite file to be created
  dim NameTable(5000) As String
  dim WidthTable(5000) As Integer
  dim HeightTable(5000) As Integer
  dim HotXTable(5000) As Integer
  dim HotYTable(5000) As Integer
  dim OffsetValue As Integer
  dim i, j, count As Integer
  dim dummy As String
  
  // color bytes
  dim myBlue, myRed, myGreen, myAlpha As Integer
  
  // TARGA header interpreting properties
  dim TargaHeaderLength As Integer
  dim TargaHeaderId As Integer
  dim TargaColorMapType, TargaImageType As Integer
  dim TargaFirstEntry, TargaColorMapLength, TargaColorMapEntrySize As Integer
  dim TargaColorDepth As Integer
  dim TargaImageDescriptor As Integer
  dim TargaTopDown As Boolean
  dim UnknownTargaFound As Boolean
  dim UnknownTargaEntry As String
  dim UnknownTargaColDepth, UnknownTargaImgType As Integer
  
  UnknownTargaFound = FALSE
  
  // constant defining
  // FormatString = "ALPH"
  
  // start user interface
  
  dlg1 = New SelectFolderDialog
  dlg1.Title = "Select Alpha-Channel-Sprites-Folder for Input"
  dlg1.ActionButtonCaption = "Select"
  dlg1.PromptText = "select a folder with the graphical content for re-building new 'TerrainA.stm'-file"
  f1 = dlg1.ShowModal
  
  if (f1 <> NIL) then
    if f1.Directory then
      InPath = f1.AbsolutePath
      DirEntries = f1.Count
      
      dlg2 = New SaveAsDialog
      dlg2.Title = "Create new File for Output"  
      dlg2.ActionButtonCaption = "Create"
      dlg2.PromptText = "enter name for the new file to re-build with " + Str(DirEntries) + " entries"
      dlg2.SuggestedFileName = "new TerrainA.stm"
      dlg2.Filter = "any file"
      f2 = dlg2.ShowModal
      
      if (f2 <> NIL) then
        // init the internal file names table
        for count = 0 to 5000
          NameTable(count) = ""
        next
        
        REM first read all filenames and files to collect header infos
        myNumberOfEntries = 0
        GreatestValueRead = -1
        UnknownTargaFound = FALSE
        for count = 1 to DirEntries
          f3 = f1.Item(count)
          if (f3 <> NIL) then
            if not f3.Directory then
              if (Len(f3.Name) >= 14) then
                if (Uppercase(Right(f3.Name, 4)) = ".TGA") and (Uppercase(Left(f3.Name, 5)) = "IMAGE") then
                  myNumberInSequence = Val(Right(Left(f3.Name, 9), 4))
                  if (myNumberInSequence >= 0) and (myNumberInSequence <= 5000) then
                    REM valid entry
                    myNumberOfEntries = myNumberOfEntries + 1
                    if (myNumberInSequence > GreatestValueRead) then
                      GreatestValueRead = myNumberInSequence
                    end
                    
                    NameTable(myNumberInSequence) = f3.AbsolutePath
                    i = Instr(f3.name,".")                // search for the first period
                    if (i = 0) or (i >= Len(f3.name)) then
                      HotXTable(myNumberInSequence) = 0
                      HotYTable(myNumberInSequence) = 0
                    else
                      i = i + 1
                      dummy = Mid(f3.name, i, 1)
                      i = i + 1
                      while (Mid(f3.name, i, 1) <> ".") and (i <= Len(f3.name))
                        dummy = dummy + Mid(f3.name, i, 1)
                        i = i + 1
                      wend
                      HotXTable(myNumberInSequence) = Val(dummy)
                      
                      i = i + 1
                      dummy = Mid(f3.name, i, 1)
                      i = i + 1
                      while (Mid(f3.name, i, 1) <> ".") and (i <= Len(f3.name))
                        dummy = dummy + Mid(f3.name, i, 1)
                        i = i + 1
                      wend
                      HotYTable(myNumberInSequence) = Val(dummy)
                    end
                    
                    InFile = f3.OpenAsBinaryFile(FALSE)
                    if (InFile <> NIL) then
                      InFile.LittleEndian = TRUE  // its a PC-like TARGA graphics file
                      
                      // check the color depth of TARGA
                      InFile.Position = 2
                      TargaImageType = InFile.ReadByte
                      InFile.Position = 16
                      TargaColorDepth = InFile.ReadByte
                      if not ((TargaImageType = 2) and (TargaColorDepth = 32)) then
                        if (not UnknownTargaFound) then
                          UnknownTargaFound = TRUE
                          UnknownTargaEntry = f3.Name
                          UnknownTargaColDepth = TargaColorDepth
                          UnknownTargaImgType = TargaImageType
                        end
                      end
                      
                      // get the image dimensions
                      InFile.Position = 12
                      WidthTable(myNumberInSequence) = InFile.ReadShort
                      HeightTable(myNumberInSequence) = InFile.ReadShort
                      
                      InFile.Close
                    end
                  end
                end
              end
            end
          end
        next
        
        // abort action if there is one or more not-32-bit Image
        if UnknownTargaFound then
          MsgBox "one or more images are not in 32-bit encoded: file " + UnknownTargaEntry + " is a " + Str(UnknownTargaColDepth) + "-bit " + App.TargaImageTypeToText(UnknownTargaImgType) + ". Operation stopped."
        else
          // all input is 32-bit clean
          
          REM now write the header
          ProgressBarTerrainA.Visible = TRUE
          ProgressBarTerrainA.Value = 0
          ProgressBarTerrainA.Maximum = GreatestValueRead
          ProgressBarTerrainA.Refresh
          
          #if TargetWin32
            OutFile = f2.CreateBinaryFile("")
          #else
            OutFile = f2.CreateBinaryFile("special/ALPH")
          #endif
          if (OutFile = NIL) then
            MsgBox "output file cannot be created."
          else
            OutFile.LittleEndian = TRUE                  // must be PC like byte order
            
            // write the header of a *.stm file (12 bytes)
            OutFile.Write("ALPH")                            // CC4/5/6/7-Format-ID
            OutFile.WriteLong(2)                             // Version ID always 2 in CC4/CC5/CCM/RtB
            OutFile.WriteLong(myNumberOfEntries)   // is a four byte value
            
            // calculate the offset of the first graphics datas
            OffsetValue = 12 + (myNumberOfEntries * 20)
            
            // write the directory (20 bytes per entry)
            for count = 0 to GreatestValueRead
              if (NameTable(count) <> "") then // we have a file there
                ProgressBarTerrainA.Value = count
                ProgressBarTerrainA.Refresh   // **** new in v2.7.3
                
                OutFile.WriteLong(HotXTable(count))   // 4 bytes
                OutFile.WriteLong(HotYTable(count))   // 4 bytes
                OutFile.WriteLong(WidthTable(count))   // 4 bytes
                OutFile.WriteLong(HeightTable(count))   // 4 bytes
                OutFile.WriteLong(OffsetValue)     // 4 bytes
                
                OffsetValue = OffsetValue + (WidthTable(count) * HeightTable(count) * 4)
              end
            next
            
            // now write the graphics datas
            for count = 0 to GreatestValueRead
              if (NameTable(count) <> "") then // we have a file there
                ProgressBarTerrainA.Value = count
                ProgressBarTerrainA.Refresh   // **** new in v2.7.3
                
                f3 = GetFolderItem(NameTable(count))
                InFile = f3.OpenAsBinaryFile(FALSE)
                if (InFile <> NIL) then
                  inFile.LittleEndian = TRUE  // its a PC-like TARGA graphics file
                  
                  // interpreting TARGA header
                  TargaHeaderId = InFile.ReadByte  // one single byte. if it is 0, then header length = 18, if it is 1 than header length = 19, etc
                  TargaHeaderLength = 18 + TargaHeaderId
                  
                  // look for color map
                  TargaColorMapType = InFile.ReadByte
                  TargaImageType = InFile.ReadByte
                  if (TargaColorMapType <> 0) then // a color map is included
                    TargaFirstEntry = InFile.ReadShort
                    TargaColorMapLength = InFile.ReadShort
                    TargaColorMapEntrySize = InFile.ReadByte   // counted in bits
                    if (TargaColorMapEntrySize >= 9) and (TargaColorMapEntrySize <= 16) then
                      TargaColorMapEntrySize = 16  // counted in bits
                    end
                    
                    TargaHeaderLength = TargaHeaderLength + ((TargaColorMapLength * TargaColorMapEntrySize) \ 8)  // counted in bytes
                  end
                  
                  // now read the data orientation
                  InFile.Position = 16
                  TargaColorDepth = InFile.ReadByte
                  TargaImageDescriptor = InFile.ReadByte
                  TargaTopDown = (BitWiseAnd(TargaImageDescriptor, 32) = 32)
                  
                  // now read the datas
                  InFile.Position = TargaHeaderLength
                  
                  for i = 1 to HeightTable(count)  // process lines
                    // respect the TARGA orientation
                    if RadioButtonTopDownA.Value then
                      if TargaTopDown then
                        InFile.Position = TargaHeaderLength + ((i - 1) * WidthTable(count) * 4)
                      else
                        InFile.Position = TargaHeaderLength + ((HeightTable(count) - i) * WidthTable(count) * 4)
                      end
                    else
                      InFile.Position = TargaHeaderLength + ((i - 1) * WidthTable(count) * 4)
                    end
                    
                    // process line
                    for j = 1 to WidthTable(count)  // process all pixels of this line
                      myRed = InFile.ReadByte()
                      myGreen = InFile.ReadByte()
                      myBlue = InFile.ReadByte()
                      myAlpha = InFile.ReadByte()
                      
                      if (myBlue > 0) then
                        myBlue = (myBlue + 1) \ 8
                      end
                      if (myGreen > 0) then
                        myGreen = (myGreen + 1) \ 8
                      end
                      if (myRed > 0) then
                        myRed = (myRed + 1) \ 8
                      end
                      if (myAlpha > 0) then
                        myAlpha = (myAlpha + 1) \ 8
                      end
                      
                      OutFile.WriteByte(myBlue)
                      OutFile.WriteByte(myGreen)
                      OutFile.WriteByte(myRed)
                      OutFile.WriteByte(myAlpha)
                    next // process all pixels of this line
                    
                  next // process all lines
                  
                  InFile.Close
                end
              end
            next // next TGA file
            
            OutFile.Close
            ProgressBarTerrainA.Visible = FALSE
          end // output file was created
        end // all input files were valid 16-bit TARGAS
      end // user selected a valid output filename
    end // its a valid input directory
  end // user selected a valid input directory
  
End Sub

WindowMain.IdentifyCC1SpriteHeader:
Function IdentifyCC1SpriteHeader(StaticCount As Integer, DirectionCount As Integer, EntryCount As Integer) As String
  dim result As String
  
  result = "unknown"
  
  if (StaticCount = 9) and (DirectionCount = 31) then
    result = "Explosion"
  elseif (StaticCount = 54) and (DirectionCount = 155) then
    result = "Rifle"
  elseif (StaticCount = 31) and (DirectionCount = 8) then
    result = "Smoke"
  elseif (StaticCount = 100) and (DirectionCount = 1) then
    result = "Terrain"
  elseif (StaticCount = 6) and (DirectionCount = 3) then
    result = "Vehicle turreted"
  elseif (StaticCount = 2) and (DirectionCount = 1) then
    result = "Vehicle"
  elseif (StaticCount = 1) and (DirectionCount = 1) then
    result = "Vehicle"
  end
  
  Return result
End Function

WindowMain.GetOriginalCC1AppendixSize:
Function GetOriginalCC1AppendixSize(StaticCount As Integer, DirectionCount As Integer) As Integer
  dim result As Integer
  
  result = 16
  
  if (StaticCount = 9) and (DirectionCount = 31) then
    result = 1300  // "Explosion"
  elseif (StaticCount = 54) and (DirectionCount = 155) then
    result = 4266  // "Rifle"
  elseif (StaticCount = 31) and (DirectionCount = 8) then
    result = 1100  // "Smoke"
  elseif (StaticCount = 100) and (DirectionCount = 1) then
    result = 1174  // "Terrain"
  elseif (StaticCount = 6) and (DirectionCount = 3) then
    result = 178  // "Vehicle turreted"
  elseif (StaticCount = 2) and (DirectionCount = 1) then
    result = 62  // "Vehicle"
  elseif (StaticCount = 1) and (DirectionCount = 1) then
    result = 52  // "Vehicle"
  end
  
  Return result
End Function

WindowMain.GetCorrectCC1ColorDepth:
Function GetCorrectCC1ColorDepth(StaticCount As Integer, DirectionCount As Integer) As Integer
  dim result As Integer
  
  result = 16
  
  if (StaticCount = 9) and (DirectionCount = 31) then
    result = 16  // "Explosion"
  elseif (StaticCount = 54) and (DirectionCount = 155) then
    result = 8  // "Rifle"
  elseif (StaticCount = 31) and (DirectionCount = 8) then
    result = 8  // "Smoke"
  elseif (StaticCount = 100) and (DirectionCount = 1) then
    result = 16  // "Terrain"
  elseif (StaticCount = 6) and (DirectionCount = 3) then
    result = 16  // "Vehicle turreted"
  elseif (StaticCount = 2) and (DirectionCount = 1) then
    result = 16  // "Vehicle"
  elseif (StaticCount = 1) and (DirectionCount = 1) then
    result = 16  // "Vehicle"
  end
  
  Return result
End Function

WindowMain.SpriteToSprite:
Sub SpriteToSprite(IsCC1File As Boolean, TargetLittleEndian As Boolean, IsSoldierFile As Boolean)
  dim InFile As BinaryStream
  dim OutFile As BinaryStream
  dim OutPath As String
  dim OutName As String
  dim dlg1 As OpenDialog
  dim dlg2 As SaveAsDialog
  dim f1, f2 As FolderItem
  dim count, i, j, filecount As Integer
  dim WhereWeAre As Integer  // for debugging purpose only
  dim trashThisPixel As Integer
  dim trashPixelCount As Integer
  dim trashPixelList As String
  dim colorPixel As Integer
  dim cRed, cGreen, cBlue As Integer
  dim whiteColorPixelCount As Integer
  dim whiteColorPixelList As String
  dim b0, b1 As Integer
  dim pixelswritten As Integer
  dim CR, TAB As String
  dim GoToPosition As Integer
  
  dim FormatStringCC2 As String
  dim FormatStringCC4 As String
  
  // header description of Sprite-File
  dim myFormatId As String
  dim myVersionId As Integer
  dim myDirectoryHeader As Integer    // must be 1000
  dim myNumberOfEntries As Integer   // for sequence 1001
  dim myNumberOfStaticAnim As Integer // for sequence 1002
  dim myNumberOfDirectionAnim As Integer // for sequence 1003
  dim myColorDepth As Integer // or number of directions ??
  dim mySpriteTableHeader As Integer   // must be 1001
  
  // header description of a single entry
  dim myWidth As Integer    // in pixel
  dim myHeight As Integer
  dim myHotspotX As Integer
  dim myHotspotY As Integer
  dim myEntrySize As Integer      // counted in bytes
  dim myLines(30000) As Integer  // line offsets
  
  dim myEntryBytesRead As Integer
  
  // color look up table (CLUT) of CC1
  dim CC1red(255) As Integer
  dim CC1green(255) As Integer
  dim CC1blue(255) As Integer
  dim myClutPic As Picture
  
  // the ouput colors we will use
  dim ColorTransparency As Integer
  dim ColorShadow As Integer
  dim ColorFillarea As Integer
  dim Color2ndShadow As Integer
  
  // sprite sequence lists
  dim spritenumbers As Integer
  dim sequenceindicator As Integer
  
  // constant defining
  FormatStringCC2 = "SPRI"   // for CC2 and CC3
  FormatStringCC4 = "IRPS"   // reverse byte format in CC4/CC5/CCM/RtB
  ColorTransparency = &h7FFF // as suggested by Cpl_Filth
  ColorShadow = &h4EE0          // as suggested by Cpl_Filth
  ColorFillarea = &h7D91         // new value by Mafi
  Color2ndShadow = &h7FE1             // new value by Mafi
  
  ColorTransparency = App.ColorToTGAvalue(App.gSpecialColor(0))
  ColorShadow = App.ColorToTGAvalue(App.gSpecialColor(1))
  ColorFillarea = App.ColorToTGAvalue(App.gSpecialColor(2))
  Color2ndShadow = App.ColorToTGAvalue(App.gSpecialColor(3))
  
  if (CC1clut125 <> NIL) then
    myClutPic = NewPicture(CC1clut125.Width, CC1clut125.Height, 32)
    if  (myClutPic <> NIL) and (myClutPic.Graphics <> NIL) then
      myClutPic.Graphics.DrawPicture(CC1clut125, 0, 0)
      for i = 0 to 255
        CC1red(i) = myClutPic.Graphics.Pixel(((i MOD 16) * 16) + 8, ((i \ 16) * 16) + 8).red
        CC1green(i) = myClutPic.Graphics.Pixel(((i MOD 16) * 16) + 8, ((i \ 16) * 16) + 8).green
        CC1blue(i) = myClutPic.Graphics.Pixel(((i MOD 16) * 16) + 8, ((i \ 16) * 16) + 8).blue
      next
    end
  end
  
  //start user interface
  dlg1 = New OpenDialog
  dlg1.Title = "Select a CC-Sprite-File for Input"
  dlg1.ActionButtonCaption = "Select"
  if IsCC1File then
    dlg1.PromptText = "select a CC1-sprite-file to be conerted."
  else
    dlg1.PromptText = "select a sprite-file to be converted."
  end
  dlg1.Filter = "any file"
  f1 = dlg1.ShowModal
  
  if (f1 <> NIL) then
    
    dlg2 = New SaveAsDialog
    dlg2.Title = "Enter Name for new File"  
    dlg2.ActionButtonCaption = "Save as"
    dlg2.PromptText = "enter name for the new file."
    dlg2.Filter = "any file"
    f2 = dlg2.ShowModal
    
    if (f2 <> NIL) then
      InFile = f1.OpenAsBinaryFile(FALSE)
      #if TargetWin32
        OutFile = f2.CreateBinaryFile("")
      #else
        if TargetLittleEndian then
          OutFile = f2.CreateBinaryFile("special/CC5sprites")
        else
          OutFile = f2.CreateBinaryFile("special/CC2sprites")
        end
      #endif
      if (InFile <> NIL) then
        if (not InFile.eof) then
          InFile.LittleEndian = FALSE   // its a Mac-born file perhaps
          // first read the header (20 bytes)
          
          myFormatId = InFile.Read(4)     // four bytes, should be "SPRI"
          if (Uppercase(myFormatId) = Uppercase(FormatStringCC2)) then
            InFile.LittleEndian = FALSE   // essential, its a Mac-born file, valid for CC2 and CC3
            myFormatId = FormatStringCC2
          elseif (Uppercase(myFormatId) = Uppercase(FormatStringCC4)) then
            InFile.LittleEndian = TRUE   // essential, its a PC-born file, valid for CC4, CC5, CCM and RoadToBaghdad
            myFormatId = FormatStringCC4
          else
            MsgBox "file format may be wrong, header found: " + myFormatId
          end
          
          if not InFile.eof then
            myVersionId = InFile.ReadLong     REM four bytes
          end
          if not InFile.eof then
            myDirectoryHeader = InFile.ReadShort   REM two bytes
          end
          if not InFile.eof then
            myNumberOfEntries = InFile.ReadShort    REM two bytes
          end
          if not InFile.eof then
            myNumberOfStaticAnim = InFile.ReadShort   REM two bytes
          end
          if not InFile.eof then
            myNumberOfDirectionAnim = InFile.ReadShort   REM two bytes
          end
          if not InFile.eof then
            myColorDepth = InFile.ReadShort   REM two bytes
          end
          if not InFile.eof then
            mySpriteTableHeader = InFile.ReadShort   REM two bytes
          end
          
          if (not InFile.eof) and (mySpriteTableHeader = 1001) and (OutFile <> NIL) then
            OutFile.LittleEndian = TargetLittleEndian
            if TargetLittleEndian then
              OutFile.Write(FormatStringCC4)
            else
              OutFile.Write(FormatStringCC2)
            end
            OutFile.WriteLong(myVersionId)
            OutFile.WriteShort(myDirectoryHeader)
            OutFile.WriteShort(myNumberOfEntries)
            OutFile.WriteShort(myNumberOfStaticAnim)
            OutFile.WriteShort(myNumberOfDirectionAnim)
            OutFile.WriteShort(myColorDepth)
            OutFile.WriteShort(mySpriteTableHeader)
            
            ProgressBarConvert.Visible = TRUE
            ProgressBarConvert.Value = 0
            ProgressBarConvert.Maximum = myNumberOfEntries
            ProgressBarConvert.Refresh
            
            GoToPosition = InFile.Position    // **** new v2.6: necessary for buggy CC3-Terrain file
            // I hope there are no additional blank bytes between header and entries
            trashPixelList = ""  // **** new v2.7.2: for whole-file bug-report
            whiteColorPixelList = ""   // **** new in v2.7.3: for additional bug reports
            
            for count = 1 to myNumberOfEntries
              trashPixelCount = 0  // **** new v2.7.2: for single sprite bug-report
              whiteColorPixelCount = 0   // **** new in v2.7.3: for additional bug reports
              ProgressBarConvert.Value = count
              ProgressBarConvert.Refresh   // **** new in v2.7.3
              // read each entry
              // first: the header: 12 bytes
              if not InFile.eof then
                myWidth = InFile.ReadShort   // two bytes
                OutFile.WriteShort(myWidth)
              end
              if not InFile.eof then
                myHeight = InFile.ReadShort   // two bytes
                OutFile.WriteShort(myHeight)
              end
              if not InFile.eof then
                myHotSpotX = InFile.ReadShort   // two bytes
                OutFile.WriteShort(myHotspotX)
              end
              if not InFile.eof then
                myHotSpotY = InFile.ReadShort   // two bytes
                OutFile.WriteShort(myHotspotY)
              end
              if not InFile.eof then
                myEntrySize = InFile.ReadLong   // four bytes
                OutFile.WriteLong(myEntrySize)
              end
              
              myEntryBytesRead = 0
              
              for i = 1 to myHeight   // (myHeight * 2) bytes
                myLines(i) = InFile.ReadShort    // two bytes per line of the image
                myEntryBytesRead = myEntryBytesRead + 2
                OutFile.WriteShort(myLines(i))
              next
              
              // now the datas, processing the line offset table
              for i = 1 to myHeight
                if (BitWiseAnd(myLines(i), &hFFFF) = &hFFFF) or (myLines(i) = -1) then  REM complete line totally blank = white = transparent
                  // do nothing
                else  REM line contains pixels
                  pixelswritten = 0
                  do
                    b0 = AscB( InFile.Read(1) )
                    OutFile.WriteByte(b0)
                    myEntryBytesRead = myEntryBytesRead + 1
                    select case b0
                      
                    case &hFF     // color pixel is coming
                      b1 = AscB( InFile.Read(1) )
                      OutFile.WriteByte(b1)
                      //if (b1 > (myWidth - pixelswritten)) then
                      // error correction for too much pixels in line definition
                      //OutFile.WriteByte((myWidth - pixelswritten) MOD 255)
                      //else
                      //OutFile.WriteByte(b1)
                      //end
                      
                      myEntryBytesRead = myEntryBytesRead + 1
                      // number of pixels is stored in b1
                      // if (b1 > myWidth) then dont correct this, otherwise pixels will be not all read!
                      //     MsgBox "Error in sprite #" + Str(filecount) + ": number of color pixels execeeds line width."
                      //    b1 = myWidth
                      // end
                      
                      if IsCC1File then // new since v2.8.2
                        for j = 1 to b1
                          if (pixelswritten < myWidth) then  // because there is an error inside the Terrain-file for pic#61 (8 pixels too much)
                            // every input pixel is always 8-bit wide !
                            colorPixel = InFile.ReadByte
                            OutFile.WriteByte(colorPixel)
                            colorPixel = App.ColorToTGAvalue(RGB(CC1red(colorPixel), CC1green(colorPixel), CC1blue(colorPixel)))
                            if BitWiseAnd(colorPixel, &hFF) = ColorTransparency then   // **** new in v2.7.3
                              whiteColorPixelCount = whiteColorPixelCount + 1
                            end
                            myEntryBytesRead = myEntryBytesRead + 1
                            pixelswritten = pixelswritten + 1
                          else
                            trashThisPixel = InFile.Readbyte    // read this one bytes to avoid miss-interpreting of pixel datas as control bytes
                            OutFile.WriteByte(trashThisPixel)
                            myEntryBytesRead = myEntryBytesRead + 1
                            trashPixelCount = trashPixelCount + 1
                          end
                        next
                      else
                        for j = 1 to b1
                          if (pixelswritten < myWidth) then  // because there is an error inside the Terrain-file for pic#61 (8 pixels too much)
                            // every pixel is always 16-bit wide !
                            // OutFile.WriteShort( InFile.ReadShort )  // take the datas as they are
                            colorPixel = InFile.ReadShort
                            OutFile.WriteShort( colorPixel )
                            if BitWiseAnd(colorPixel, &hFFFF) = ColorTransparency then   // **** new in v2.7.3
                              whiteColorPixelCount = whiteColorPixelCount + 1
                            end
                            myEntryBytesRead = myEntryBytesRead + 2
                            pixelswritten = pixelswritten + 1
                          else
                            // **** new in v2.7.1
                            trashThisPixel = InFile.ReadShort    // read this two bytes to avoid miss-interpreting of pixel datas as control bytes
                            OutFile.WriteShort( trashThisPixel )
                            myEntryBytesRead = myEntryBytesRead + 2
                            // dont write this pixel.
                            // but remember the amount, **** new in v2.7.2
                            trashPixelCount = trashPixelCount + 1
                          end
                        next
                      end
                      
                    case &h00     // transparency pixel is coming
                      b1 = AscB( InFile.Read(1) )
                      OutFile.WriteByte(b1)
                      myEntryBytesRead = myEntryBytesRead + 1
                      // number of pixels is stored in b1
                      // write this amount of transparent pixels
                      for j = 1 to b1
                        pixelswritten = pixelswritten + 1
                      next
                      
                    case &hF5    // shadow pixel is coming
                      b1 = AscB( InFile.Read(1) )
                      OutFile.WriteByte(b1)
                      myEntryBytesRead = myEntryBytesRead + 1
                      // write this amount of shadow pixels
                      for j = 1 to b1
                        pixelswritten = pixelswritten + 1
                      next
                      
                    case &hF7     // special pixel for "fill-area" purpose, used by crosshairs in Terrain
                      b1 = AscB( InFile.Read(1) )
                      OutFile.WriteByte(b1)
                      myEntryBytesRead = myEntryBytesRead + 1
                      // write this amount of special pixels
                      for j = 1 to b1
                        pixelswritten = pixelswritten + 1
                      next
                      
                    case &hF9     // special pixel for "white" purpose, used by big trees in Terrain
                      b1 = AscB( InFile.Read(1) )
                      OutFile.WriteByte(b1)
                      myEntryBytesRead = myEntryBytesRead + 1
                      // write this amount of special pixels
                      for j = 1 to b1
                        pixelswritten = pixelswritten + 1
                      next
                      
                    case &hED      // line end specifier - fill the rest of the line with white pixels
                      // nothing do follow
                      
                    else
                      if (b0 >= &hC0) and (b0 <= &hC9) then   // soldier pixel is coming, not in CC1
                        b1 = AscB( InFile.Read(1) )
                        OutFile.WriteByte(b1)
                        myEntryBytesRead = myEntryBytesRead + 1
                        // number of pixels is stored in b1
                        for j = 1 to b1
                          // provisional: treat them like color pixels, but should be reported as mask
                          // ***** this must be debugged next time!! -> reporting to mask must be added!!
                          if (pixelswritten < myWidth) then
                            // every pixel is always 16-bit wide !
                            OutFile.WriteShort( InFile.ReadShort )  // take the datas as they are
                            myEntryBytesRead = myEntryBytesRead + 2
                            pixelswritten = pixelswritten + 1
                          else
                            // **** new in v2.7.1
                            trashThisPixel = InFile.ReadShort    // read this two bytes to avoid miss-interpreting of pixel datas as control bytes
                            OutFile.WriteShort( trashThisPixel )
                            myEntryBytesRead = myEntryBytesRead + 2
                            // dont write this pixel.
                            // but remember the amount, **** new in v2.7.2
                            trashPixelCount = trashPixelCount + 1
                          end
                        next
                      else
                        // dont report this to avoid multiple MsgBoxes without aborting
                        //WhereWeAre = InFile.Position
                        //MsgBox "at input-file-offset " + Hex(WhereWeAre - 1) + "h - error in sprite #" + Str(filecount) + ", unknown line descriptor found: " + Hex(b0) + "h"
                      end
                    end select
                  loop until (b0 = &hED)
                end
              next
              
              // special for CC4/CC5/CCM/RtB-Terrain and *.spr file: trailing zero byte must be read after last line
              if (myFormatId = FormatStringCC4) and (not IsCC1File) and (not IsSoldierFile) then
                while (myEntryBytesRead < myEntrySize)
                  b0 = AscB( InFile.Read(1) )
                  if TargetLittleEndian then
                    OutFile.WriteByte(b0)
                  end
                  myEntryBytesRead = myEntryBytesRead + 1
                  
                  //if (b0 <> 0) then
                  //   MsgBox "error in last byte of sprite #" + Str(filecount)
                  //end
                  
                  // b0 must be &h00
                wend
              else
                if TargetLittleEndian and (not IsCC1File) and (not IsSoldierFile) then
                  OutFile.WriteByte( 0 )  // trailing zero byte required
                end
              end
              
              
              // **** new in v2.7.2
              if (trashPixelCount > 0) then
                if (Len(trashPixelList) > 0) then
                  trashPixelList = trashPixelList + ", "
                end
                trashPixelList = trashPixelList + "sprite #" + Str(FileCount) + " has " + Str(trashPixelCount) + " pixels"
              end
              
              // **** new in v2.7.3
              if (whiteColorPixelCount > 0) then
                if (Len(whiteColorPixelList) > 0) then
                  whiteColorPixelList = whiteColorPixelList + ", "
                end
                whiteColorPixelList = whiteColorPixelList + "sprite #" + Str(FileCount) + " has " + Str(whiteColorPixelCount) + " transparent pixels"
              end
              
              
              // done for this entry
              
              // skip padding additional empty bytes
              // myEntryBytesRead = myEntrySize should be identical
              GoToPosition = GoToPosition + myEntrySize + 12    // **** new v2.6: necessary for buggy CC3-Terrain file
              InFile.Position = GoToPosition                                 // **** new v2.6: necessary for buggy CC3-Terrain file
              
            next
            
            
            ProgressBarConvert.Visible = FALSE
            
            // now reading and extracting the appendix
            
            count = 0 // used as sequence counter
            while not InFile.EOF
              b0 = InFile.ReadShort
              OutFile.WriteShort( b0 )
              
              // read sequence-section header
              select case b0
              case &h03EA
                count = -1
                sequenceindicator = b0
              case &h03EB
                count = -1
                sequenceindicator = b0
              else
                count = count + 1
                spritenumbers = b0
                // style_indicator
                b0 = InFile.ReadShort
                OutFile.WriteShort( b0 )
                // Unknown_1
                b0 = InFile.ReadShort
                OutFile.WriteShort( b0 )
                if (sequenceindicator = &h03EA) then // has Unknown_2
                  b0 = InFile.ReadShort
                  OutFile.WriteShort( b0 )
                end
                // number list
                for i = 0 to (spritenumbers - 1)
                  b0 = InFile.ReadShort
                  OutFile.WriteShort( b0 )
                next
              end select
              
            wend
            
          end
          
          if (OutFile <> NIL) then
            OutFile.Close
          end
          
          // **** new in v2.7.2: bug report
          if (Len(trashPixelList) > 0) then
            MsgBox "Found: " + trashPixelList + " too much. These pixels will be not removed."
          end
          
          // **** new in v2.7.3: bug report
          if (Len(whiteColorPixelList) > 0) then
            MsgBox "Found: " + whiteColorPixelList + " coded as color pixels, which were written as white color pixels." 
          end
          
        else
          MsgBox "empty file: " + f1.Name
        end
        InFile.Close
      end
      
    end
    
  end
  
End Sub

WindowMain.TilesToTiles:
Sub TilesToTiles(TargetLittleEndian As Boolean)
  dim InFile As BinaryStream
  dim OutFile As BinaryStream
  dim dlg1 As OpenDialog
  dim dlg2 As SaveAsDialog
  dim f1, f2 As FolderItem
  dim count, i As Integer
  dim IsCC1File As Boolean
  
  dim FormatStringCC2 As String
  dim FormatStringCC4 As String
  
  // header description of Sprite-File
  dim myFormatId As String
  dim myVersionId As Integer
  dim myNumberOfEntries As Integer   // for Tiles
  
  // header description of a single entry
  dim myWidth As Integer    // in pixel
  dim myHeight As Integer
  dim myEntrySize As Integer      // counted in bytes
  
  // color look up table (CLUT) of CC1
  dim CC1red(255) As Integer
  dim CC1green(255) As Integer
  dim CC1blue(255) As Integer
  dim myClutPic As Picture
  
  // constant defining
  FormatStringCC2 = "TILE"   // for Mac version
  FormatStringCC4 = "ELIT"   // reverse byte format for PC version
  IsCC1File = TRUE // always CC1
  
  if (CC1clut125 <> NIL) then
    myClutPic = NewPicture(CC1clut125.Width, CC1clut125.Height, 32)
    if  (myClutPic <> NIL) and (myClutPic.Graphics <> NIL) then
      myClutPic.Graphics.DrawPicture(CC1clut125, 0, 0)
      for i = 0 to 255
        CC1red(i) = myClutPic.Graphics.Pixel(((i MOD 16) * 16) + 8, ((i \ 16) * 16) + 8).red
        CC1green(i) = myClutPic.Graphics.Pixel(((i MOD 16) * 16) + 8, ((i \ 16) * 16) + 8).green
        CC1blue(i) = myClutPic.Graphics.Pixel(((i MOD 16) * 16) + 8, ((i \ 16) * 16) + 8).blue
      next
    end
  end
  
  //start user interface
  dlg1 = New OpenDialog
  dlg1.Title = "Select a CC1-Tiles-File for Input"
  dlg1.ActionButtonCaption = "Select"
  if IsCC1File then
    dlg1.PromptText = "select a CC1-Tiles-file to be conerted."
  else
    dlg1.PromptText = "select a Tiles-file to be converted."
  end
  dlg1.Filter = "any file"
  f1 = dlg1.ShowModal
  
  if (f1 <> NIL) then
    
    dlg2 = New SaveAsDialog
    dlg2.Title = "Enter Name for new File"  
    dlg2.ActionButtonCaption = "Save as"
    dlg2.PromptText = "enter name for the new file."
    dlg2.Filter = "any file;special/CC1tiles"
    if TargetLittleEndian then
      dlg2.SuggestedFileName = "TILES new"
    else
      dlg2.SuggestedFileName = "Terran Tiles new"
    end
    f2 = dlg2.ShowModal
    
    if (f2 <> NIL) then
      InFile = f1.OpenAsBinaryFile(FALSE)
      #if TargetWin32
        OutFile = f2.CreateBinaryFile("")
      #else
        if TargetLittleEndian then
          OutFile = f2.CreateBinaryFile("special/CC1tiles")
        else
          OutFile = f2.CreateBinaryFile("special/CC1tiles")
        end
      #endif
      if (InFile <> NIL) then
        if (not InFile.eof) then
          InFile.LittleEndian = FALSE   // its a Mac-born file perhaps
          // first read the header (20 bytes)
          
          myFormatId = InFile.Read(4)     // four bytes, should be "TILE"
          if (Uppercase(myFormatId) = Uppercase(FormatStringCC2)) then
            InFile.LittleEndian = FALSE   // essential, its a Mac-born file CC1
            myFormatId = FormatStringCC2
          elseif (Uppercase(myFormatId) = Uppercase(FormatStringCC4)) then
            InFile.LittleEndian = TRUE   // essential, its a PC-born file CC1
            myFormatId = FormatStringCC4
          else
            MsgBox "file format may be wrong, header found: " + myFormatId
          end
          
          if not InFile.eof then
            myVersionId = InFile.ReadLong     REM four bytes, should be 00010000hex
          end
          if not InFile.eof then
            myNumberOfEntries = InFile.ReadLong    REM four bytes
          end
          
          if (not InFile.eof) and (OutFile <> NIL) then
            OutFile.LittleEndian = TargetLittleEndian
            if TargetLittleEndian then
              OutFile.Write(FormatStringCC4)
            else
              OutFile.Write(FormatStringCC2)
            end
            OutFile.WriteLong(myVersionId)
            OutFile.WriteLong(myNumberOfEntries)
            
            ProgressBarConvert.Visible = TRUE
            ProgressBarConvert.Value = 0
            ProgressBarConvert.Maximum = myNumberOfEntries
            ProgressBarConvert.Refresh
            
            myWidth = 40  // always fixed size
            myHeight = 40
            myEntrySize = myWidth * myHeight // 8-bit color = 1 byte = 1 pixel
            
            for count = 1 to myNumberOfEntries
              ProgressBarConvert.Value = count
              ProgressBarConvert.Refresh   // **** new in v2.7.3
              // read each entry
              // no header, always fixed size of 1600 bytes
              if not InFile.eof then
                OutFile.Write( InFile.Read(myEntrySize) )
              end
            next
            
            ProgressBarConvert.Visible = FALSE
            
            if (OutFile <> NIL) then
              OutFile.Close
            end
            
          else
            MsgBox "empty file: " + f1.Name
          end
        end
        InFile.Close
      end
    end
  end
  
End Sub

WindowMain.TilesToTGA:
Sub TilesToTGA()
  dim InFile As BinaryStream
  dim OutFile As BinaryStream
  dim dlg1 As OpenDialog
  dim dlg2 As SelectFolderDialog
  dim f1, f2, f3 As FolderItem
  dim OutPath, OutName As String
  dim count, i, filecount As Integer
  dim colorPixel As Integer
  dim IsCC1File As Boolean
  
  dim FormatStringCC2 As String
  dim FormatStringCC4 As String
  
  // header description of Sprite-File
  dim myFormatId As String
  dim myVersionId As Integer
  dim myNumberOfEntries As Integer   // for Tiles
  
  // header description of a single entry
  dim myWidth As Integer    // in pixel
  dim myHeight As Integer
  dim myEntrySize As Integer      // counted in bytes
  
  // color look up table (CLUT) of CC1
  dim CC1red(255) As Integer
  dim CC1green(255) As Integer
  dim CC1blue(255) As Integer
  dim myClutPic As Picture
  
  // constant defining
  FormatStringCC2 = "TILE"   // for Mac version
  FormatStringCC4 = "ELIT"   // reverse byte format for PC version
  IsCC1File = TRUE // always CC1
  
  if (CC1clut125 <> NIL) then
    myClutPic = NewPicture(CC1clut125.Width, CC1clut125.Height, 32)
    if  (myClutPic <> NIL) and (myClutPic.Graphics <> NIL) then
      myClutPic.Graphics.DrawPicture(CC1clut125, 0, 0)
      for i = 0 to 255
        CC1red(i) = myClutPic.Graphics.Pixel(((i MOD 16) * 16) + 8, ((i \ 16) * 16) + 8).red
        CC1green(i) = myClutPic.Graphics.Pixel(((i MOD 16) * 16) + 8, ((i \ 16) * 16) + 8).green
        CC1blue(i) = myClutPic.Graphics.Pixel(((i MOD 16) * 16) + 8, ((i \ 16) * 16) + 8).blue
      next
    end
  end
  
  //start user interface
  dlg1 = New OpenDialog
  dlg1.Title = "Select a CC1-Tiles-File for Input"
  dlg1.ActionButtonCaption = "Select"
  if IsCC1File then
    dlg1.PromptText = "select a CC1-Tiles-file to be conerted."
  else
    dlg1.PromptText = "select a Tiles-file to be Extracted."
  end
  dlg1.Filter = "any file"
  f1 = dlg1.ShowModal
  
  if (f1 <> NIL) then
    
    dlg2 = New SelectFolderDialog
    dlg2.Title = "Select Folder for new Files"  
    dlg2.ActionButtonCaption = "Select"
    dlg2.PromptText = "select folder to store the new files."
    dlg2.Filter = "any file"
    f2 = dlg2.ShowModal
    
    if (f2 <> NIL) then
      OutPath = f2.AbsolutePath
      #if TargetWin32
        if (Right(OutPath, 1) <> "\") then
          OutPath = OutPath + "\"
        end
      #else
        if (Right(OutPath, 1) <> ":") then
          OutPath = OutPath + ":"
        end
      #endif
      InFile = f1.OpenAsBinaryFile(FALSE)
      if (InFile <> NIL) then
        if (not InFile.eof) then
          InFile.LittleEndian = FALSE   // its a Mac-born file perhaps
          // first read the header (20 bytes)
          
          myFormatId = InFile.Read(4)     // four bytes, should be "TILE"
          if (Uppercase(myFormatId) = Uppercase(FormatStringCC2)) then
            InFile.LittleEndian = FALSE   // essential, its a Mac-born file CC1
            myFormatId = FormatStringCC2
          elseif (Uppercase(myFormatId) = Uppercase(FormatStringCC4)) then
            InFile.LittleEndian = TRUE   // essential, its a PC-born file CC1
            myFormatId = FormatStringCC4
          else
            MsgBox "file format may be wrong, header found: " + myFormatId
          end
          
          if not InFile.eof then
            myVersionId = InFile.ReadLong     REM four bytes, should be 00010000hex
          end
          if not InFile.eof then
            myNumberOfEntries = InFile.ReadLong    REM four bytes
          end
          
          if (not InFile.eof) and (OutPath <> "") then
            
            ProgressBarExtract.Visible = TRUE
            ProgressBarExtract.Value = 0
            ProgressBarExtract.Maximum = myNumberOfEntries
            ProgressBarExtract.Refresh
            
            myWidth = 40  // always fixed size
            myHeight = 40
            myEntrySize = myWidth * myHeight // 8-bit color = 1 byte = 1 pixel
            
            for count = 1 to myNumberOfEntries
              ProgressBarExtract.Value = count
              ProgressBarExtract.Refresh   // **** new in v2.7.3
              
              // create output filename
              if RadioButtonCountZero.Value then
                filecount = count - 1
              else
                filecount = count
              end
              OutName = OutPath + "Tile"
              if (filecount < 10) then
                OutName = OutName + "0"
              end
              if (filecount < 100) then
                OutName = OutName + "0"
              end
              if (filecount < 1000) then
                OutName = OutName + "0"
              end
              OutName = OutName + Str(filecount) + ".tga"
              
              // create output file
              f3 = GetFolderItem(OutName)
              
              if (f3 <> NIL) then
                #if TargetWin32
                  OutFile = f3.CreateBinaryFile("")
                #else
                  OutFile = f3.CreateBinaryFile("image/x-targa")
                #endif
                if (OutFile <> NIL) then
                  OutFile.LittleEndian = TRUE   REM because it is a PC-like TARGA graphics file
                  
                  // first: the TARGA-header
                  OutFile.WriteShort(0)     // no ID, no color map
                  OutFile.WriteShort(2)     // Image Type: uncompressed True-Color
                  OutFile.WriteLong(0)      // no color map
                  OutFile.WriteLong(0)      // image origin lower left
                  OutFile.WriteShort(myWidth)
                  OutFile.WriteShort(myHeight)
                  OutFile.WriteByte(16)   // Color Depth 16-bit
                  if RadioButtonTopDown.Value then
                    OutFile.WriteByte(33)   // Image Descriptor: ignore 1 bit, top-to-bottom and left-to-right pixel orientation
                  else
                    OutFile.WriteByte(1)   // Image Descriptor: ignore 1 bit, bottom-to-top and left-to-right pixel orientation
                  end
                  
                  // read each entry
                  // no header, always fixed size of 1600 bytes
                  
                  // is always IsCC1File 
                  for i = 1 to myEntrySize
                    // every input pixel is always 8-bit wide !
                    colorPixel = InFile.ReadByte
                    colorPixel = App.ColorToTGAvalue(RGB(CC1red(colorPixel), CC1green(colorPixel), CC1blue(colorPixel)))
                    OutFile.WriteShort ( colorPixel )
                  next
                  
                  OutFile.Close
                end  // outfile was created
              end // place to store folderitem is valid
            next
            
            ProgressBarExtract.Visible = FALSE
            
          else
            MsgBox "empty file: " + f1.Name
          end
        end
        InFile.Close
      end
    end
  end
  
End Sub

WindowMain.TGAToSprite:
Sub TGAToSprite(SpriteType As String)
  dim InFile As BinaryStream
  dim OutFile As BinaryStream
  dim dlg2 As SaveAsDialog
  dim dlg1 As SelectFolderDialog
  dim f1, f2, f3 As FolderItem
  dim InPath As String
  dim OutName As String
  dim DirEntries As Integer
  dim AppendixFileFound, VersionIDfileFound As Boolean
  dim IsCC4Sprite As Boolean
  
  dim GreatestValueRead As Integer          // out of all external TARGA files
  dim myNumberInSequence As Integer      // of this external TARGA file
  dim myNumberOfEntries As Integer        // resulting for the sprite file to be created
  dim myNumberOfStaticAnim, myNumberOfDirectionAnim, myFoundNumberOfStaticAnim, myFoundNumberOfDirectionAnim As Integer
  dim NameTable(5000) As String
  dim WidthTable(5000) As Integer
  dim HeightTable(5000) As Integer
  dim HotXTable(5000) As Integer
  dim HotYTable(5000) As Integer
  dim dummy As String
  dim i, j, k, count As Integer
  dim transparentCount As Integer
  dim coloredCount As Integer
  dim shadowedCount As Integer
  dim filledCount As Integer
  dim whiteCount As Integer
  dim PixelReadNew, PixelReadBefore As Integer
  dim BytesPerLine, OffsetStart As Integer
  dim PixelBuffer(10000) As Integer
  dim PixelBufferSize As Integer
  dim NumberOfColoredLines As Integer
  dim SpecialCounter As Integer
  dim LineBufferSize(10000) As Integer
  dim LineBuffer(10000, 10000) As Integer
  dim OffsetBuffer(10000) As Integer
  dim ErrorFirstLineOutOfSize As Integer
  
  // the output colors we will use
  dim ColorTransparency As Integer
  dim ColorShadow As Integer
  dim ColorFillarea As Integer
  dim Color2ndShadow As Integer
  
  // TARGA header interpreting properties
  dim TargaHeaderLength As Integer
  dim TargaHeaderId As Integer
  dim TargaColorMapType, TargaImageType As Integer
  dim TargaFirstEntry, TargaColorMapLength, TargaColorMapEntrySize As Integer
  dim TargaColorDepth As Integer
  dim TargaImageDescriptor As Integer
  dim TargaTopDown As Boolean
  dim UnknownTargaFound As Boolean
  dim UnknownTargaEntry As String
  dim UnknownTargaColDepth, UnknownTargaImgType As Integer
  
  UnknownTargaFound = FALSE
  
  // constant defining
  // FormatString = "SPRI"
  IsCC4Sprite =  (SpriteType = "CC4TERRAIN") or (SpriteType = "CC5TERRAIN") or (SpriteType = "CCMTERRAIN") or (SpriteType = "RTBTERRAIN") or (SpriteType = "CCMTTERRAIN") or (SpriteType = "SPRfile") or (SpriteType = "CC4SOLDIER") or (SpriteType = "CC4SOLDIERB") or (SpriteType = "CCWARTERRAIN") or (SpriteType = "CCTLDTERRAIN") or (SpriteType = "CCLSATERRAIN")
  
  ColorTransparency = &h7FFF // as suggested by Cpl_Filth
  ColorShadow = &h4EE0          // as suggested by Cpl_Filth
  ColorFillarea = &h7D91         // new value by Mafi
  Color2ndShadow = &h7FE1             // new value by Mafi
  
  ColorTransparency = App.ColorToTGAvalue(App.gSpecialColor(0))
  ColorShadow = App.ColorToTGAvalue(App.gSpecialColor(1))
  ColorFillarea = App.ColorToTGAvalue(App.gSpecialColor(2))
  Color2ndShadow = App.ColorToTGAvalue(App.gSpecialColor(3))
  
  // start user interface
  
  dlg1 = New SelectFolderDialog
  dlg1.Title = "Select Sprites-Folder for Input"
  dlg1.ActionButtonCaption = "Select"
  if IsCC4Sprite then
    if (SpriteType = "SPRfile") then
      dlg1.PromptText = "select a folder with the graphics for re-building new CC4/RtB '*.spr'-file"
    else
      dlg1.PromptText = "select a folder with the graphics for re-building new '" + SpriteType + "'-file"
    end
  else
    if (SpriteType = "CC3TERRAIN") then
      dlg1.PromptText = "select a folder with the graphics for re-building new CC3-Terrain-file"
    elseif (SpriteType = "CC3NSD") then
      dlg1.PromptText = "select a folder with the graphics for re-building new CC3 '*.nsd'-file"
    elseif (SpriteType = "CC3ZSD") then
      dlg1.PromptText = "select a folder with the graphics for re-building new CC3 '*.zsd'-file"
    else
      dlg1.PromptText = "select a folder with the graphics for re-building new CC2-'" + SpriteType + "'-file"
    end
  end
  f1 = dlg1.ShowModal
  
  if (f1 <> NIL) then
    if f1.Directory then
      InPath = f1.AbsolutePath
      DirEntries = f1.Count
      
      dlg2 = New SaveAsDialog
      dlg2.Title = "Create new File for Output"  
      dlg2.ActionButtonCaption = "Create"
      dlg2.PromptText = "enter name for the new file to re-build with " + Str(DirEntries - 2) + " entries"
      if (SpriteType = "SPRfile") then
        dlg2.SuggestedFileName = "new Shadow.spr"
      elseif (SpriteType = "CC3NSD") then
        dlg2.SuggestedFileName = "new Shadow.nsd"
      elseif (SpriteType = "CC3ZSD") then
        dlg2.SuggestedFileName = "new Shadow.zsd"
      else
        dlg2.SuggestedFileName = SpriteType + " new"
      end
      dlg2.Filter = "any file"
      f2 = dlg2.ShowModal
      
      if (f2 <> NIL) then
        // init the internal file names table
        for count = 0 to 5000
          NameTable(count) = ""
        next
        
        REM first read all filenames and files to collect header infos
        myNumberOfEntries = 0
        GreatestValueRead = -1
        UnknownTargaFound = FALSE
        for count = 1 to DirEntries
          f3 = f1.Item(count)
          if (f3 <> NIL) then
            if not f3.Directory then
              if (Len(f3.Name) >= 14) then
                if (Uppercase(Right(f3.Name, 4)) = ".TGA") and (Uppercase(Left(f3.Name, 5)) = "IMAGE") then
                  myNumberInSequence = Val(Right(Left(f3.Name, 9), 4))
                  if (myNumberInSequence >= 0) and (myNumberInSequence <= 5000) then
                    REM valid entry
                    myNumberOfEntries = myNumberOfEntries + 1
                    if (myNumberInSequence > GreatestValueRead) then
                      GreatestValueRead = myNumberInSequence
                    end
                    
                    NameTable(myNumberInSequence) = f3.AbsolutePath
                    i = Instr(f3.name,".")                // search for the first period
                    if (i = 0) or (i >= Len(f3.name)) then
                      HotXTable(myNumberInSequence) = 0
                      HotYTable(myNumberInSequence) = 0
                    else
                      i = i + 1
                      dummy = Mid(f3.name, i, 1)
                      i = i + 1
                      while (Mid(f3.name, i, 1) <> ".") and (i <= Len(f3.name))
                        dummy = dummy + Mid(f3.name, i, 1)
                        i = i + 1
                      wend
                      HotXTable(myNumberInSequence) = Val(dummy)
                      
                      i = i + 1
                      dummy = Mid(f3.name, i, 1)
                      i = i + 1
                      while (Mid(f3.name, i, 1) <> ".") and (i <= Len(f3.name))
                        dummy = dummy + Mid(f3.name, i, 1)
                        i = i + 1
                      wend
                      HotYTable(myNumberInSequence) = Val(dummy)
                    end
                    
                    InFile = f3.OpenAsBinaryFile(FALSE)
                    if (InFile <> NIL) then
                      InFile.LittleEndian = TRUE  // its a PC-like TARGA graphics file
                      
                      // check the color depth of TARGA
                      InFile.Position = 2
                      TargaImageType = InFile.ReadByte
                      InFile.Position = 16
                      TargaColorDepth = InFile.ReadByte
                      if not ((TargaImageType = 2) and ((TargaColorDepth = 16) or (TargaColorDepth = 15))) then
                        if (not UnknownTargaFound) then
                          UnknownTargaFound = TRUE
                          UnknownTargaEntry = f3.Name
                          UnknownTargaColDepth = TargaColorDepth
                          UnknownTargaImgType = TargaImageType
                        end
                      end
                      
                      // get the image dimensions
                      InFile.Position = 12
                      WidthTable(myNumberInSequence) = InFile.ReadShort
                      HeightTable(myNumberInSequence) = InFile.ReadShort
                      
                      InFile.Close
                    end
                  end
                end
              end
            end
          end
        next
        
        // abort action if there is one or more not-16-bit Image
        if UnknownTargaFound then
          MsgBox "one or more images are not in 16-bit encoded: file " + UnknownTargaEntry + " is a " + Str(UnknownTargaColDepth) + "-bit " + App.TargaImageTypeToText(UnknownTargaImgType) + ". Operation stopped."
        else
          // all input is 16-bit clean
          
          REM now write the header
          ProgressBarRebuild.Visible = TRUE
          ProgressBarRebuild.Value = 0
          ProgressBarRebuild.Maximum = GreatestValueRead
          ProgressBarRebuild.Refresh
          
          #if TargetWin32
            OutFile = f2.CreateBinaryFile("")
          #else
            if IsCC4Sprite then
              OutFile = f2.CreateBinaryFile("special/CC5sprites")
            else
              if (SpriteType = "CC3NSD") or (SpriteType = "CC3ZSD") or (SpriteType = "CC3Terrain") then
                OutFile = f2.CreateBinaryFile("special/CC3sprites")
              else
                OutFile = f2.CreateBinaryFile("special/CC2sprites")
              end
            end
          #endif
          if (OutFile = NIL) then
            MsgBox "output file cannot be created."
          else
            myNumberOfStaticAnim = GetCorrectAmountStaticAnim(SpriteType, myNumberOfEntries)
            myNumberOfDirectionAnim = GetCorrectAmountDirectionAnim(SpriteType, myNumberOfEntries)
            if IsCC4Sprite then 
              OutFile.LittleEndian = TRUE                  // must be PC like byte order
              OutFile.Write("IRPS")                            // CC4/5/6/7-Format-ID
            else
              OutFile.LittleEndian = FALSE
              OutFile.Write("SPRI")                            // CC2/CC3-Format-ID
            end
            
            // special handling for  version-ID for *.spr files
            
            f3 = GetFolderItem(InPath + "VersionID.bin")
            VersionIDfileFound = (f3 <> NIL)
            
            if VersionIDfileFound then
              InFile = f3.OpenAsBinaryFile(FALSE)
              VersionIDfileFound = (InFile <> NIL)
              if VersionIDfileFound then
                InFile.LittleEndian = FALSE  // it doesnt matter in that case because we will read each byte seperately
                
                while not InFile.EOF
                  OutFile.WriteByte( InFile.ReadByte )
                  // if we would read short or long we must determine the byte order first!
                wend
                
                InFile.Close
              end
            end
            
            if not VersionIDfileFound then 
              OutFile.WriteLong(1)                             // Version ID always 1 in CC2 / CC3
            end
            
            OutFile.WriteShort(1000)                      // Directory-Header is always 1000 in CC2
            OutFile.WriteShort(myNumberOfEntries)   // is a two byte value in CC2
            OutFile.WriteShort(myNumberOfStaticAnim)
            OutFile.WriteShort(myNumberOfDirectionAnim)
            OutFile.WriteShort(GetCorrectColorDepth( myNumberOfStaticAnim, myNumberOfDirectionAnim, not IsCC4Sprite) )
            OutFile.WriteShort(1001)                      // Sprite-Table-Header is always 1001 in CC2
            
            REM now write the entries
            
            for count = 0 to GreatestValueRead
              if (NameTable(count) <> "") then // we have a file there
                ProgressBarRebuild.Value = count
                ProgressBarRebuild.Refresh   // **** new in v2.7.3
                
                f3 = GetFolderItem(NameTable(count))
                
                // write the entry header
                OutFile.WriteShort(WidthTable(count))   // picture width
                OutFile.WriteShort(HeightTable(count))  // picture height
                OutFile.WriteShort(HotXTable(count))     // hotspot X
                OutFile.WriteShort(HotYTable(count))    // hotspot Y
                
                // read the complete file to calculate the entry
                InFile = f3.OpenAsBinaryFile(FALSE)
                if (InFile <> NIL) then
                  inFile.LittleEndian = TRUE  // its a PC-like TARGA graphics file
                  
                  // interpreting TARGA header
                  TargaHeaderId = InFile.ReadByte  // one single byte. if it is 0, then header length = 18, if it is 1 than header length = 19, etc
                  TargaHeaderLength = 18 + TargaHeaderId
                  
                  // look for color map
                  TargaColorMapType = InFile.ReadByte
                  TargaImageType = InFile.ReadByte
                  if (TargaColorMapType <> 0) then // a color map is included
                    TargaFirstEntry = InFile.ReadShort
                    TargaColorMapLength = InFile.ReadShort
                    TargaColorMapEntrySize = InFile.ReadByte   // counted in bits
                    if (TargaColorMapEntrySize >= 9) and (TargaColorMapEntrySize <= 16) then
                      TargaColorMapEntrySize = 16  // counted in bits
                    end
                    
                    TargaHeaderLength = TargaHeaderLength + ((TargaColorMapLength * TargaColorMapEntrySize) \ 8)  // counted in bytes
                  end
                  
                  // now read the data orientation
                  InFile.Position = 16
                  TargaColorDepth = InFile.ReadByte
                  TargaImageDescriptor = InFile.ReadByte
                  TargaTopDown = (BitWiseAnd(TargaImageDescriptor, 32) = 32)
                  
                  // now read the datas
                  InFile.Position = TargaHeaderLength
                  
                  OffsetStart = 0                     // beginning of datas of first colored pixel
                  NumberOfColoredLines = 0    // no lines with pixels yet
                  for i = 1 to HeightTable(count)  // process lines
                    // respect the TARGA orientation
                    if RadioButtonRespectTGAheader.Value then
                      if TargaTopDown then
                        InFile.Position = TargaHeaderLength + ((i - 1) * WidthTable(count) * 2)
                      else
                        InFile.Position = TargaHeaderLength + ((HeightTable(count) - i) * WidthTable(count) * 2)
                      end
                    else
                      InFile.Position = TargaHeaderLength + ((i - 1) * WidthTable(count) * 2)
                    end
                    
                    LineBufferSize(i) = 0
                    PixelReadBefore = &hFFFF
                    PixelBufferSize = 0
                    SpecialCounter = 0
                    for j = 1 to WidthTable(count)  // process all pixels of this line
                      PixelReadNew = InFile.ReadShort
                      
                      if (PixelReadNew = ColorTransparency) or (PixelReadNew = ColorShadow) or (PixelReadNew = ColorFillarea) or (PixelReadNew = Color2ndShadow) then
                        // is a special color
                        if (PixelReadNew <> PixelReadBefore) and (PixelReadBefore <> &hFFFF) then
                          if (PixelBufferSize > 0) then
                            // transfer all color pixels to the line buffer
                            LineBufferSize(i) = LineBufferSize(i) + 1
                            if IsCC4Sprite then
                              LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(PixelBufferSize, 8) + &hFF
                            else
                              // CC2 & CC3
                              LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(&hFF, 8) + PixelBufferSize
                            end
                            for k = 1 to PixelBufferSize
                              LineBufferSize(i) = LineBufferSize(i) + 1
                              LineBuffer(i, LineBufferSize(i)) = PixelBuffer(k)
                            next
                            PixelBufferSize = 0
                          else
                            // transfer special char and length byte to the line buffer
                            LineBufferSize(i) = LineBufferSize(i) + 1
                            select case PixelReadBefore
                            case ColorTransparency
                              if IsCC4Sprite then
                                LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(SpecialCounter, 8) + &h00
                              else
                                // CC2 & CC3
                                LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(&h00, 8) + SpecialCounter
                              end
                            case ColorShadow
                              if IsCC4Sprite then
                                LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(SpecialCounter, 8) + &hF5
                              else
                                // CC2 & CC3
                                LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(&hF5, 8) + SpecialCounter
                              end
                            case ColorFillarea
                              if IsCC4Sprite then
                                LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(SpecialCounter, 8) + &hF7
                              else
                                // CC2 & CC3
                                LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(&hF7, 8) + SpecialCounter
                              end
                            case Color2ndShadow
                              if IsCC4Sprite then
                                LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(SpecialCounter, 8) + &hF9
                              else
                                // CC2 & CC3
                                LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(&hF9, 8) + SpecialCounter
                              end
                            end select
                          end
                          SpecialCounter = 1 // we start with a new special color
                        else
                          SpecialCounter = SpecialCounter + 1
                        end
                      else // its a colored Pixel
                        if (SpecialCounter > 0) then
                          // transfer special char and length byte to the line buffer
                          LineBufferSize(i) = LineBufferSize(i) + 1
                          select case PixelReadBefore
                          case ColorTransparency
                            if IsCC4Sprite then
                              LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(SpecialCounter, 8) + &h00
                            else
                              // CC2 & CC3
                              LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(&h00, 8) + SpecialCounter
                            end
                          case ColorShadow
                            if IsCC4Sprite then
                              LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(SpecialCounter, 8) + &hF5
                            else
                              // CC2 & CC3
                              LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(&hF5, 8) + SpecialCounter
                            end
                          case ColorFillarea
                            if IsCC4Sprite then
                              LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(SpecialCounter, 8) + &hF7
                            else
                              // CC2 & CC3
                              LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(&hF7, 8) + SpecialCounter
                            end
                          case Color2ndShadow
                            if IsCC4Sprite then
                              LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(SpecialCounter, 8) + &hF9
                            else
                              // CC2 & CC3
                              LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(&hF9, 8) + SpecialCounter
                            end
                          end select
                        end
                        SpecialCounter = 0
                        PixelBufferSize = PixelBufferSize + 1
                        PixelBuffer(PixelBufferSize) = PixelReadNew
                      end
                      PixelReadBefore = PixelReadNew
                    next // process all pixels of this line
                    
                    if ((SpecialCounter = WidthTable(count)) and ((PixelReadBefore = ColorTransparency) or (PixelReadBefore = &hFFFF))) and (not IsCC4Sprite) then
                      // entire line is transparent, no pixel datas preserved
                      OffsetBuffer(i) = &hFFFF
                    else
                      if (PixelBufferSize > 0) then
                        // transfer all color pixels to the line buffer
                        LineBufferSize(i) = LineBufferSize(i) + 1
                        if IsCC4Sprite then
                          LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(PixelBufferSize, 8) + &hFF
                        else
                          // CC2 & CC3
                          LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(&hFF, 8) + PixelBufferSize
                        end
                        for k = 1 to PixelBufferSize
                          LineBufferSize(i) = LineBufferSize(i) + 1
                          LineBuffer(i, LineBufferSize(i)) = PixelBuffer(k)
                        next
                        PixelBufferSize = 0
                      elseif (SpecialCounter > 0) then
                        select case PixelReadBefore
                        case ColorTransparency
                          if IsCC4Sprite then
                            LineBufferSize(i) = LineBufferSize(i) + 1
                            LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(SpecialCounter, 8) + &h00
                          else
                            // CC2 & CC3
                            // only in CC2 and CC3 the transparency pixels remaining will be resolved by end-of-line byte
                          end
                        case ColorShadow
                          LineBufferSize(i) = LineBufferSize(i) + 1
                          if IsCC4Sprite then
                            LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(SpecialCounter, 8) + &hF5
                          else
                            // CC2 & CC3
                            LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(&hF5, 8) + SpecialCounter
                          end
                        case ColorFillarea
                          LineBufferSize(i) = LineBufferSize(i) + 1
                          if IsCC4Sprite then
                            LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(SpecialCounter, 8) + &hF7
                          else
                            // CC2 & CC3
                            LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(&hF7, 8) + SpecialCounter
                          end
                        case Color2ndShadow
                          LineBufferSize(i) = LineBufferSize(i) + 1
                          if IsCC4Sprite then
                            LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(SpecialCounter, 8) + &hF9
                          else
                            // CC2 & CC3
                            LineBuffer(i, LineBufferSize(i)) = Bitwise.ShiftLeft(&hF9, 8) + SpecialCounter
                          end
                        end select
                        // only in CC2 and CC3 the transparency pixels remaining will be resolved by end-of-line byte
                        SpecialCounter = 0
                      end
                      // the end-of-line byte will be added later
                      OffsetBuffer(i) = OffsetStart
                      OffsetStart = OffsetStart + (LineBufferSize(i) * 2) + 1
                      NumberOfColoredLines = NumberOfColoredLines + 1
                    end
                  next // process all lines
                  
                  InFile.Close
                end
                
                // now write the last entry of the header: the offset-table + data size
                if IsCC4Sprite then
                  // something special: an additional zero byte after the last &hED, so the size is one byte larger than in CC2
                  OutFile.WriteLong((HeightTable(count) * 2) + OffsetStart + 1)     // size of offset-table + pixel data
                else
                  // CC2 and CC3
                  OutFile.WriteLong((HeightTable(count) * 2) + OffsetStart)     // size of offset-table + pixel data
                end
                
                // write the offset table
                ErrorFirstLineOutOfSize = -1
                for i = 1 to HeightTable(count)
                  if (OffsetBuffer(i) > &hFFFF) then
                    // new in v2.9.4: checking for images which are too big
                    OutFile.WriteShort(&hFFFF)  // size to big for SHORT, code this line as WHITE as a compromise
                    // do not set OffsetBuffer(i) = &hFFFF, this will corrupt the internal offset calculations,
                    // in other words: you must define these lines as whites, but you must write their pixels
                    // to get proper offset calculations for the next image...
                    if (ErrorFirstLineOutOfSize < 0) then
                      ErrorFirstLineOutOfSize = i
                    end
                  else
                    OutFile.WriteShort(OffsetBuffer(i))
                  end
                next
                if (ErrorFirstLineOutOfSize >= 0) then
                  MsgBox("Image #" + Str(count) + " too large (" + Str(WidthTable(count)) + "x" + Str(HeightTable(count)) + " pixels). Starting with line " + Str(ErrorFirstLineOutOfSize) + ", the image will be filled with white lines.")
                end
                
                // write the compressed pixel datas
                for i = 1 to HeightTable(count)
                  if (OffsetBuffer(i) <> &hFFFF) then // this line has datas
                    for j = 1 to LineBufferSize(i)
                      OutFile.WriteShort(LineBuffer(i, j))
                    next
                    OutFile.WriteByte(&hED)   // write end-of-line byte
                  end
                next
                if IsCC4Sprite then
                  // something special: an additional zero byte after the last &hED, so the size is one byte larger than in CC2
                  OutFile.WriteByte(0)        // write end-of-entry byte = zero
                end
                // job done for this entry
                
              end // of we have a file there
            next // entry processing
            
            // now add the appendix/footer
            f3 = GetFolderItem(InPath + "Appendix.bin")
            AppendixFileFound = (f3 <> NIL)
            
            if AppendixFileFound then
              // new in v2.9.1: check the number of entries inside Appendix.bin
              AppendixFileFound = AnalyzeAppendixFile(f3, myFoundNumberOfStaticAnim, myFoundNumberOfDirectionAnim)
              
              if AppendixFileFound then
                // control the number of entries
                if (myFoundNumberOfStaticAnim <> myNumberOfStaticAnim) then
                  MsgBox("Number of Static-Animations found inside '" + f3.Name + "' is " + Str(myFoundNumberOfStaticAnim) + " (should be originally " + Str(myNumberOfStaticAnim) + "). Header will be patched accordingly.")
                  OutFile.Position = 12
                  OutFile.WriteShort(myFoundNumberOfStaticAnim)
                end
                if (myFoundNumberOfDirectionAnim <> myNumberOfDirectionAnim) then
                  MsgBox("Number of Direction-based-Animations found inside '" + f3.Name + "' is " + Str(myFoundNumberOfDirectionAnim) + " (should be originally " + Str(myNumberOfDirectionAnim) + "). Header will be patched accordingly.")
                  OutFile.Position = 14
                  OutFile.WriteShort(myFoundNumberOfDirectionAnim)
                end
              end
              
              // append Appendix.bin
              OutFile.Position = OutFile.Length
              InFile = f3.OpenAsBinaryFile(FALSE)
              AppendixFileFound = (InFile <> NIL)
              if AppendixFileFound then
                InFile.LittleEndian = FALSE  // it doesnt matter in that case because we will read each byte seperately
                
                while not InFile.EOF
                  OutFile.WriteByte( InFile.ReadByte )
                  // if we would read short or long we must determine the byte order first!
                wend
                
                InFile.Close
              end
            end
            
            if not AppendixFileFound then 
              if (SpriteType = "VehB") or (SpriteType = "VehS") then
                // generate a valid appendix from scratch
                
                if (myNumberOfEntries >= 64) then
                  // its a turreted vehicle
                  OutFile.WriteShort( &h03EA )   // header-ID
                  OutFile.WriteShort( 1 )            // number of sprites in sequence
                  OutFile.WriteShort( &h2200 )  // style indicator
                  OutFile.WriteShort( 0 )            // unknown
                  OutFile.WriteShort( 0 )            // unknown
                  OutFile.WriteShort( 0 )           // sprite-number
                  OutFile.WriteShort( 1 )            // number of sprites in sequence
                  OutFile.WriteShort( &h2200 )  // style indicator
                  OutFile.WriteShort( 0 )            // unknown
                  OutFile.WriteShort( 0 )            // unknown
                  OutFile.WriteShort( 1 )           // sprite-number
                  OutFile.WriteShort( 1 )            // number of sprites in sequence
                  OutFile.WriteShort( &h2220 )  // style indicator
                  OutFile.WriteShort( 0 )            // unknown
                  OutFile.WriteShort( 0 )            // unknown
                  OutFile.WriteShort( 0 )           // sprite-number
                  
                  OutFile.WriteShort( &h03EB )   // header-ID
                  OutFile.WriteShort( 32 )          // number of sprites in sequence
                  OutFile.WriteShort( 0 )            // unknown
                  OutFile.WriteShort( 0 )            // unknown
                  for i = 0 to 31
                    OutFile.WriteShort( i )           // sprite-number for hull
                  next
                  OutFile.WriteShort( 32 )          // number of sprites in sequence
                  OutFile.WriteShort( 0 )            // unknown
                  OutFile.WriteShort( 0 )            // unknown
                  for i = 32 to 63
                    OutFile.WriteShort( i )           // sprite-number for gun/turret
                  next
                  
                else
                  // its turretless
                  OutFile.WriteShort( &h03EA )   // header-ID
                  OutFile.WriteShort( 1 )            // number of sprites in sequence
                  OutFile.WriteShort( &h2200 )  // style indicator
                  OutFile.WriteShort( 0 )            // unknown
                  OutFile.WriteShort( 0 )            // unknown
                  OutFile.WriteShort( 0 )           // sprite-number
                  OutFile.WriteShort( 1 )            // number of sprites in sequence
                  OutFile.WriteShort( &h2220 )  // style indicator
                  OutFile.WriteShort( 0 )            // unknown
                  OutFile.WriteShort( 0 )            // unknown
                  OutFile.WriteShort( 0 )           // sprite-number
                  
                  OutFile.WriteShort( &h03EB )   // header-ID
                  OutFile.WriteShort( 32 )          // number of sprites in sequence
                  OutFile.WriteShort( 0 )            // unknown
                  OutFile.WriteShort( 0 )            // unknown
                  for i = 0 to 31
                    OutFile.WriteShort( i )           // sprite-number
                  next
                end
              elseif (SpriteType = "SPRfile") then
                // its a turreted vehicle
                OutFile.WriteShort( &h03EA )   // header-ID
                OutFile.WriteShort( 1 )            // number of sprites in sequence
                OutFile.WriteShort( &hFFF2 )  // style indicator
                OutFile.WriteShort( &hF51C )            // unknown
                OutFile.WriteShort( &h0068 )            // unknown
                OutFile.WriteShort( 0 )           // sprite-number
                
                OutFile.WriteShort( &h03EB )   // header-ID
                OutFile.WriteShort( 64 )          // number of sprites in sequence
                OutFile.WriteShort( &hFFF2 )  // style indicator
                OutFile.WriteShort( &hF51C )            // unknown
                for i = 0 to 63
                  OutFile.WriteShort( i )           // sprite-number
                next
              elseif (SpriteType = "CC3NSD") or (SpriteType = "CC3ZSD") then
                //  turreted doesnt matter ???
                OutFile.WriteShort( &h03EA )   // header-ID
                OutFile.WriteShort( 1 )            // number of sprites in sequence
                OutFile.WriteShort( &h2200 )  // style indicator
                OutFile.WriteShort( &h0000 )            // unknown
                OutFile.WriteShort( &h0000 )            // unknown
                OutFile.WriteShort( 0 )           // sprite-number
                
                OutFile.WriteShort( &h03EB )   // header-ID
                OutFile.WriteShort( 64 )          // number of sprites in sequence
                OutFile.WriteShort( &h0000 )  // style indicator
                OutFile.WriteShort( &h0000 )            // unknown
                for i = 0 to 63
                  OutFile.WriteShort( i )           // sprite-number
                next
                
              else
                MsgBox "Appendix.bin file not found for adding, file will not work in CC"
              end
            end
            
            OutFile.Close
            ProgressBarRebuild.Visible = FALSE
          end // output file was created
        end // all input files were valid 16-bit TARGAS
      end // user selected a valid output filename
    end // its a valid input directory
  end // user selected a valid input directory
  
End Sub

WindowMain.AnalyzeAppendixFile:
Function AnalyzeAppendixFile(thisAppendixFile As FolderItem, ByRef thisStaticAnimationsFound As Integer, ByRef thisDirectionAnimationsFound As Integer) As Boolean
  dim noFileError As Boolean
  dim InFile As BinaryStream
  dim count, i,  b0 As Integer
  dim s As String
  
  // header and directory description
  dim SequenceHeader As String
  dim myNumberOfFrames As Integer
  
  // init of returned byRef values
  thisStaticAnimationsFound = 0
  thisDirectionAnimationsFound = 0  
  noFileError = FALSE
  
  if (thisAppendixFile <> NIL) then
    
    InFile = thisAppendixFile.OpenAsBinaryFile(FALSE)
    if (InFile <> NIL) then
      InFile.LittleEndian = FALSE   REM essential, its a Mac-born file (CC2 + CC3)
      if not InFile.eof then
        // scan entire Appendix.bin file
        // first read the header (2 bytes)
        noFileError = TRUE
        SequenceHeader = InFile.Read(2)
        
        // determine byte format
        if (SequenceHeader = (Chr(&hEA) + Chr(&h03))) then
          InFile.LittleEndian = TRUE    // essential, its a PC-born file (CC4, CC5, CCM, RtB)
          //gFileFormat = "INTEL"
        elseif (SequenceHeader = (Chr(&h03) + Chr(&hEA))) then
          InFile.LittleEndian = FALSE  // essential, its a Mac-born file (CC2 + CC3)
          //gFileFormat = "MOTOROLA"
        else
          MsgBox "its probably no valid 'Appendix.bin' file."
        end
        
        // read entries
        count = -1
        do
          b0 = InFile.ReadShort
          if (b0 = &h03EB) then
            SequenceHeader = Chr(&h03) + Chr(&hEB)
          else
            count = count + 1
            myNumberOfFrames = b0
            
            for i = 2 to 4
              b0 = InFile.ReadShort
            next
            
            for i = 0 to (myNumberOfFrames - 1)
              b0 = InFile.ReadShort
            next
          end
        loop until (b0 = &h03EB) or InFile.EOF
        
        //StaticTextEA.Text = "static animations (indicator 03EAhex): " + Str(count + 1) + " found"
        thisStaticAnimationsFound = count + 1
        
        count = -1
        if not InFile.EOF then
          do
            b0 = InFile.ReadShort
            count = count + 1
            myNumberOfFrames = b0
            
            for i = 2 to 3
              b0 = InFile.ReadShort
            next
            
            for i = 0 to (myNumberOfFrames - 1)
              b0 = InFile.ReadShort
            next
          loop until InFile.EOF
        end
        
        //StaticTextEB.Text = "direction-oriented animations (indicator 03EBhex): " + Str(count + 1) + " found"
        thisDirectionAnimationsFound = count + 1
      else
        MsgBox "empty file: " + thisAppendixFile.Name
      end
      
      InFile.Close
    end
  end
  
  // returned values will be modified "byRef"
  Return noFileError
End Function

WindowMain.Resized:
Sub Resized()
  StaticTextHead1.Width = me.Width
  StaticTextHead2.Width = me.Width
  TabPanel1.Width = me.Width - 30
  Tabpanel1.Height = me.Height - 60
  ListBoxAnalyze.Width = TabPanel1.Width - 22
  ListBoxAnalyze.Height = TabPanel1.Height - 95
  ProgressBarAnalyze.Top = ListBoxAnalyze.Top + ListBoxAnalyze.Height + 10
  ProgressBarAnalyze.Width = ListBoxAnalyze.Width
  ProgressBarConvert.Top = ProgressBarAnalyze.Top
  ProgressBarConvert.Width = ProgressBarConvert.Width
  ProgressBarExtract.Top = ProgressBarAnalyze.Top
  ProgressBarExtract.Width = ProgressBarConvert.Width
  ProgressBarRebuild.Top = ProgressBarAnalyze.Top
  ProgressBarRebuild.Width = ProgressBarConvert.Width
  ProgressBarTerrainA.Top = ProgressBarAnalyze.Top
  ProgressBarTerrainA.Width = ProgressBarConvert.Width
End Sub

WindowMain.PushButton2.Action:
Sub Action()
  AnalyzeSpriteFile
End Sub

WindowMain.PushButtonExtractCC2.Action:
Sub Action()
  SpriteToTGA(FALSE, FALSE)
End Sub

WindowMain.PushButton3.Action:
Sub Action()
  WindowColorSetting.Visible = TRUE
  WindowColorSetting.Show
End Sub

WindowMain.PushButton9.Action:
Sub Action()
  WindowAppendixEdit.Visible = TRUE
  WindowAppendixEdit.Show
End Sub

WindowMain.PushButton13.Action:
Sub Action()
  WindowZFX.Visible = TRUE
  WindowZFX.Show
End Sub

WindowMain.RadioButtonCountZero.Action:
Sub Action()
  RadioButtonCountOne.Value = not me.Value
End Sub

WindowMain.RadioButtonCountOne.Action:
Sub Action()
  RadioButtonCountZero.Value = not me.Value
End Sub

WindowMain.PushButtonRebuildCC2Explode.Action:
Sub Action()
  TGAToSprite("Explode")
End Sub

WindowMain.PushButtonRebuildCC2Smoke.Action:
Sub Action()
  TGAToSprite("Smoke")
End Sub

WindowMain.PushButtonRebuildCC2Terrain.Action:
Sub Action()
  TGAToSprite("Terrain")
End Sub

WindowMain.PushButtonRebuildCC2VehB.Action:
Sub Action()
  TGAToSprite("VehB")
End Sub

WindowMain.PushButtonRebuildCC2VehS.Action:
Sub Action()
  TGAToSprite("VehS")
End Sub

WindowMain.PushButtonRebuildCC3Terrain.Action:
Sub Action()
  TGAToSprite("CC3TERRAIN")
End Sub

WindowMain.PushButtonRebuildCC5Terrain.Action:
Sub Action()
  TGAToSprite("CC5TERRAIN")
End Sub

WindowMain.PushButtonREbuildRtBTerrain.Action:
Sub Action()
  TGAToSprite("RTBTERRAIN")
End Sub

WindowMain.PushButtonRebuildCC4Terrain.Action:
Sub Action()
  TGAToSprite("CC4TERRAIN")
End Sub

WindowMain.PushButtonRebuildCCM3Terrain.Action:
Sub Action()
  TGAToSprite("CCMTERRAIN")
End Sub

WindowMain.RadioButtonTopDown.Action:
Sub Action()
  RadioButtonFlipped.Value = FALSE
End Sub

WindowMain.RadioButtonFlipped.Action:
Sub Action()
  RadioButtonTopDown.Value = FALSE
End Sub

WindowMain.RadioButtonRespectTGAheader.Action:
Sub Action()
  RadioButtonIgnoreTGAheader.Value = FALSE
End Sub

WindowMain.RadioButtonIgnoreTGAheader.Action:
Sub Action()
  RadioButtonRespectTGAheader.Value = FALSE
End Sub

WindowMain.PushButton16.Action:
Sub Action()
  SaveReportToFile
End Sub

WindowMain.RadioButtonCountZeroA.Action:
Sub Action()
  RadioButtonCountOneA.Value = not me.Value
End Sub

WindowMain.RadioButtonCountOneA.Action:
Sub Action()
  RadioButtonCountZeroA.Value = not me.Value
End Sub

WindowMain.RadioButtonTopDownA.Action:
Sub Action()
  RadioButtonFlippedA.Value = FALSE
End Sub

WindowMain.RadioButtonFlippedA.Action:
Sub Action()
  RadioButtonTopDownA.Value = FALSE
End Sub

WindowMain.PushButton17.Action:
Sub Action()
  AlphToTGA(TRUE, 32)
End Sub

WindowMain.PushButton18.Action:
Sub Action()
  TGAToAlph
End Sub

WindowMain.PushButton19.Action:
Sub Action()
  AlphToTGA(TRUE, 16)
End Sub

WindowMain.PushButton20.Action:
Sub Action()
  AlphToTGA(FALSE, 16)
End Sub

WindowMain.PushButtonRebuildSPR.Action:
Sub Action()
  TGAToSprite("SPRfile")
End Sub

WindowMain.PushButtonRebuildCC3NSD.Action:
Sub Action()
  TGAToSprite("CC3NSD")
End Sub

WindowMain.PushButtonRebuildCC3ZSD.Action:
Sub Action()
  TGAToSprite("CC3ZSD")
End Sub

WindowMain.PushButtonExtractCC1.Action:
Sub Action()
  SpriteToTGA(TRUE, FALSE)
End Sub

WindowMain.PushButtonShowCLUT.Action:
Sub Action()
  WindowCC1clut.Show
  WindowCC1clut.Visible = TRUE
End Sub

WindowMain.PushButtonConvert.Action:
Sub Action(Index As Integer)
  SpriteToSprite(Index <= 1, (Index MOD 2) = 0, Index >= 2)
End Sub

WindowMain.PushButtonConvertTiles.Action:
Sub Action(Index As Integer)
  TilesToTiles((Index MOD 2) = 0)
End Sub

WindowMain.PushButtonExtractTiles.Action:
Sub Action()
  TilesToTGA
End Sub

WindowMain.PushButtonExtractSoldier.Action:
Sub Action()
  SpriteToTGA(FALSE, TRUE)
End Sub

WindowMain.PushButtonRebuildCC4Soldier.Action:
Sub Action()
  TGAToSoldierSprite("CC4SOLDIER")
End Sub

WindowMain.PushButtonRebuildCC4SoldierB.Action:
Sub Action()
  TGAToSoldierSprite("CC4SOLDIERB")
End Sub

WindowMain.PushButtonRebuildCC2Soldier.Action:
Sub Action()
  TGAToSoldierSprite("SOLDIER")
End Sub

WindowMain.PushButtonRebuildCC2SoldierB.Action:
Sub Action()
  TGAToSoldierSprite("SOLDIERB")
End Sub

WindowMain.PushButtonShowReservedSolCol.Action:
Sub Action()
  WindowSoldierColors.Visible = TRUE
  WindowSoldierColors.Show
End Sub

WindowMain.PushButtonRebuildCCMTTerrain.Action:
Sub Action()
  TGAToSprite("CCMTTERRAIN")  // CCMT-Terrain is identical with CCM-Terrain
End Sub

WindowMain.PushButtonRebuildWaRTerrain.Action:
Sub Action()
  TGAToSprite("CCWARTERRAIN")  // is identical with TLD-Terrain
End Sub

WindowMain.PushButtonRebuildTLDTerrain.Action:
Sub Action()
  TGAToSprite("CCTLDTERRAIN")
End Sub

WindowMain.PushButtonRebuildLSATerrain.Action:
Sub Action()
  TGAToSprite("CCLSATERRAIN")
End Sub

App.ColorToTGAvalue:
Function ColorToTGAvalue(InputColor As Color) As Integer
  // pixel value calculation as reported by Gerry Shaw aka 'Tin Tin'
  dim myRed, myGreen, myBlue As Integer
  
  // the first right 3 bits must be deleted
  myRed = Bitwise.ShiftRight(InputColor.red, 3)
  myGreen = Bitwise.ShiftRight(InputColor.green, 3)
  myBlue = Bitwise.ShiftRight(InputColor.blue, 3)
  
  // and only 5 bits per color will survive
  Return Bitwise.ShiftLeft( BitWise.BitAnd(myRed, 31), 10) + Bitwise.ShiftLeft( BitWise.BitAnd(myGreen, 31), 5) + BitWise.BitAnd(myBlue, 31) 
End Function

App.TargaImageTypeToText:
Function TargaImageTypeToText(ImageType As Integer) As String
  select case ImageType
  case 0                
    Return "No Image Data Included"
  case 1
    Return "Uncompressed, Color-mapped Image"
  case 2
    Return "Uncompressed, True-color Image"
  case 3
    Return "Uncompressed, Black-and-white Image"
  case 9
    Return "RLE-compressed, Color-mapped Image"
  case 10
    Return "RLE-compressed, True-color Image"
  case 11
    Return "RLE-compressed, Black-and-white Image"
  else
    Return "unknown Image Type"
  end
End Function

App.AddPathDelimiter:
Function AddPathDelimiter(PathName As String) As String
  #if TargetWin32
    if (Len(Pathname) > 0) then
      if (Right(Pathname,1) <> "\") then
        Return Pathname + "\"
      else
        Return Pathname
      end
    else
      Return Pathname
    end
  #else
    if (Len(Pathname) > 0) then
      if (Right(Pathname,1) <> ":") then
        Return Pathname + ":"
      else
        Return Pathname
      end
    else
      Return Pathname
    end
  #endif
  
End Function

App.TGAvalueToColor:
Function TGAvalueToColor(myPixel As Integer) As Color
  // myPixel =  InFile.ReadShort
  
  // the CC2 Bit order of each Pixel: 0RRRRRGGGGGBBBBB
  // the ShiftLeft of 3 bits later on is for the hue
  //myRed = BitWise.ShiftLeft(BitWise.BitAnd(BitWise.ShiftRight(myPixel, 10), &h1F), 3)
  //myGreen = BitWise.ShiftLeft(BitWise.BitAnd(BitWise.ShiftRight(myPixel, 5), &h1F), 3)
  //myBlue = BitWise.ShiftLeft(BitWise.BitAnd(myPixel, &h1F), 3)
  
  Return RGB(BitWise.ShiftLeft(BitWise.BitAnd(BitWise.ShiftRight(myPixel, 10), &h1F), 3), BitWise.ShiftLeft(BitWise.BitAnd(BitWise.ShiftRight(myPixel, 5), &h1F), 3), BitWise.ShiftLeft(BitWise.BitAnd(myPixel, &h1F), 3))
  
End Function

App.HexToInt:
Function HexToInt(s As String) As Integer
  dim result As Integer
  dim cropped As String
  
  result = 0
  if (Len(s) > 0) then
    if (Len(s) > 2) and (Uppercase(Left(s,2)) = "0X") then
      cropped = Right(s,Len(s) - 2)
    elseif (Uppercase(Right(s,3)) = "HEX") then
      cropped = Left(s,Len(s) - 3)
    elseif (Uppercase(Right(s,3)) = "&XH") then
      cropped = Left(s,Len(s) - 3)
    elseif (Uppercase(Right(s,2)) = "XH") then
      cropped = Left(s,Len(s) - 2)
    elseif (Uppercase(Right(s,1)) = "H") then
      cropped = Left(s,Len(s) - 1)
    elseif (Uppercase(Left(s,2)) = "HEX") then
      cropped = Right(s,Len(s) - 3)
    elseif (Uppercase(Left(s,2)) = "&H") then
      cropped = Right(s,Len(s) - 2)
    elseif (Uppercase(Left(s,2)) = "XH") then
      cropped = Right(s,Len(s) - 2)
    elseif (Uppercase(Left(s,2)) = "HX") then
      cropped = Right(s,Len(s) - 2)
    elseif (Uppercase(Left(s,1)) = "H") then
      cropped = Right(s,Len(s) - 1)
    else
      cropped= s
    end
    
    result = Val("&H" + cropped)
    
  end
  
  Return result
End Function

App.gmIsNumerical:
Function gmIsNumerical(s As String) As Boolean
  dim i As Integer
  dim result As Boolean
  
  if (s = "") then
    Return FALSE
  else
    result = TRUE
    for i = 1 to Len(s)
      if (Mid(s, i, 1) < "0") or (Mid(s, i, 1) > "9") then
        result = FALSE
        Exit
      end
    next
    Return result
  end
  
End Function

App.SetWindowModified:
Sub SetWindowModified(w as window, b as boolean)
  // 68k/Carbon version for RB 5.5.4 from: http://www.mactech.com/articles/mactech/Vol.17/17.12/Dec01REALbasic/index.html
  
  // from: http://jjlange.spymac.com/other1.html</string>
  // Added 11/15/2001 by Jarvis Badgley
  // Modified 2/3/2002 by Kevin Ballard
  
  // Shows a little dot in the red close box of MacOS-X
  // modified by Mafi for use with PPC/MachO/Intel Macs 2007-04-01
  
  
  Dim cDot As String
  #if TargetWin32
    cDot = ChrB(183) // kleiner schwarzer Punkt
  #endif
  
  #if TargetMacOS
    cDot = ChrB(165)
  #endif
  
  #if RBversion < 2005
    #if TargetMacOS then
      #if Target68k then
        // No 68k code
      #else
        // requires MacOS 8.5 or newer!
        Dim osErr As Integer
        
        #if TargetCarbon
          Declare Function IsWindowModified Lib "CarbonLib" (window as WindowPtr) as Boolean
          Declare Function SetWindowModified Lib "CarbonLib" (window as WindowPtr, modified as Boolean) as Integer
        #else
          Declare Function IsWindowModified Lib "WindowsLib" (window as WindowPtr) as Boolean
          Declare Function SetWindowModified Lib "WindowsLib" (window as WindowPtr, modified as Integer) as Integer  // must be all integer for Classic in RB 5.5.4
        #endif
        
        osErr=SetWindowModified(w, b)
        
      #endif // Target68k
    #endif // TargetMacOS
  #endif  // RBversion < 2005
  
  #if (RBVersion < 2007) and (RBversion >= 2005)  // no Intel support
    #if TargetMacOS
      Dim osErr As Integer
      
      #if TargetMachO
        // fuer MachO X 2005/2006
        #if TargetCarbon then
          Declare Function SetWindowModified Lib "Carbon" (window As WindowPtr, modified As Integer) As Integer
        #else
          Declare Function SetWindowModified Lib "WindowsLib" (window As WindowPtr, modified As Integer) As Integer
        #endif
        
        osErr=SetWindowModified(w,b)  // strange, defined as "Integer" but must get "Boolean"
      #else
        // fuer 9/X 2005/2006
        // is not working for Classic in RealBasic 2006.01
      #endif
    #endif
  #endif   // RBversion = 2005/2006
  
  #if RBVersion >= 2007
    #if TargetMacOS
      Dim osErr As Integer
      dim v as variant
      
      #if TargetPowerPC
        #if TargetMachO
          // fuer UniversalBinary X 2007
          #if TargetCarbon then
            Declare Function SetWindowModified Lib "Carbon" (window As WindowPtr, modified As Boolean) As Integer
          #else
            Declare Function SetWindowModified Lib "WindowsLib" (window As WindowPtr, modified As Boolean) As Integer
          #endif
          
          v=b
          osErr=SetWindowModified(w,v)
        #else
          // fuer 9/X 2007
          #if TargetCarbon then
            Declare Function SetWindowModified Lib "CarbonLib" (window As WindowPtr, modified As Integer) As Integer
          #else
            Declare Function SetWindowModified Lib "WindowsLib" (window As WindowPtr, modified As Integer) As Integer
          #endif
          
          v=b
          osErr=SetWindowModified(w,v)
        #endif
      #else
        // fuer Intel X 2007
        #if TargetCarbon then
          Declare Function SetWindowModified Lib "Carbon" (window As WindowPtr, modified As Integer) As Integer
        #else
          Declare Function SetWindowModified Lib "WindowsLib" (window As WindowPtr, modified As Integer) As Integer
        #endif
        
        v=b
        osErr=SetWindowModified(w,v)
      #endif
    #endif
  #endif   // RBversion >= 2007
  
  // now for all platforms: adding a small dot at the end of the window  title
  if b then
    if (LenB(w.Title) > 2) and (RightB(w.Title,1) = cDot) then
      // has already dot
    else
      w.Title = w.Title + " " + cDot
    end
  else
    if (LenB(w.Title) > 2) and (RightB(w.Title,1) = cDot) then
      w.Title = LeftB(w.Title, LenB(w.Title) - 2)
    end
  end
  
  
End Sub

App.CreateNewBlackTriangleForMenu:
Sub CreateNewBlackTriangleForMenu()
  dim i As Integer
  
  gBlackTriangleForMenu = NewPicture(16, 12, 16)
  if (gBlackTriangleForMenu <> NIL) and (gBlackTriangleForMenu.Graphics <> NIL) then
    gBlackTriangleForMenu.Transparent = 1  // use white as transparent
    gBlackTriangleForMenu.Graphics.UseOldRenderer = TRUE
    gBlackTriangleForMenu.Graphics.PenHeight = 1
    gBlackTriangleForMenu.Graphics.PenWidth = 1
    gBlackTriangleForMenu.Graphics.ForeColor = &c000000  // Black
    gBlackTriangleForMenu.Graphics.DrawLine(7, 6, 15, 6)
    for i = 0 to 4
      gBlackTriangleForMenu.Graphics.DrawLine(7 + i, 7 + i, 15 - i, 7 + i)
    next
  end
End Sub

App.Open:
Sub Open()
  gAppVersion = ShortVersion
  // initialize gBlackTriangleForMenu
  CreateNewBlackTriangleForMenu
  // initialize gSpecialColors
  WindowColorSetting.RestoreMafisSettings
  WindowColorSetting.Visible = FALSE
End Sub

WindowColorSetting.RestoreMafisSettings:
Sub RestoreMafisSettings()
  // side-effect: modyfies global property gSpecialColor
  dim CRchar As String
  dim myColor As Color
  dim i As Integer
  
  #if TargetWin32
    CRchar = Chr(13) + Chr(10)
  #else
    CRchar = Chr(13)
  #endif
  
  // initialize the RGB-value description
  for i = 0 to 3 
    CanvasSpecialColors(i).Backdrop = NewPicture(60, 30, 16)
  next
  CanvasSpecialColors(0).Backdrop.Graphics.DrawPicture(TransparencyColor, 0, 0)
  CanvasSpecialColors(1).Backdrop.Graphics.DrawPicture(ShadowColor, 0, 0)
  CanvasSpecialColors(2).Backdrop.Graphics.DrawPicture(FillareaColor, 0, 0)
  CanvasSpecialColors(3).Backdrop.Graphics.DrawPicture(Shadow2ndColor, 0, 0)
  for i = 0 to 3
    if (CanvasSpecialColors(i).Backdrop.Graphics <> NIL) then
      myColor = CanvasSpecialColors(i).Backdrop.Graphics.Pixel(1,1)
    else
      myColor = RGB(0,0,0)
    end
    App.gSpecialColor(i) = myColor
    ValuesSpecialColors(i).Text = Left(ValuesSpecialColors(i).Text, 21) + CRchar + "RGB value=(" + Hex(myColor.Red) + "h, " + Hex(myColor.Green) + "h, " + Hex(myColor.Blue) + "h)"
    ValuesSpecialColors(i).Text = ValuesSpecialColors(i).Text + CRchar + "16-bit pixel-value = " + Hex(App.ColorToTGAvalue(myColor)) + "h"
    CanvasSpecialColors(i).Backdrop.Graphics.ForeColor = RGB(0, 0, 0) // black
    CanvasSpecialColors(i).Backdrop.Graphics.DrawRect(0,0,60,30) // draw a black frame around the picture
  next
  
End Sub

WindowColorSetting.ChangeColorForActiveCanvas:
Sub ChangeColorForActiveCanvas()
  // side-effect: modyfies global property App.gSpecialColor
  dim b As Boolean
  dim CRchar As String
  
  #if TargetWin32
    CRchar = Chr(13) + Chr(10)
  #else
    CRchar = Chr(13)
  #endif
  
  if (ActiveCanvas = -1) then
    MsgBox "Please select the special color you want to change..."
  else
    newColor = App.gSpecialColor(ActiveCanvas)
    b = SelectColor(newColor, "Select a new color for " + TitleSpecialColors(ActiveCanvas).Text)
    if b then
      ValuesSpecialColors(ActiveCanvas).Text = Left(ValuesSpecialColors(ActiveCanvas).Text, 21) + CRchar + "RGB value=(" + Hex(newColor.Red) + "h, " + Hex(newColor.Green) + "h, " + Hex(newColor.Blue) + "h)"
      ValuesSpecialColors(ActiveCanvas).Text = ValuesSpecialColors(ActiveCanvas).Text + CRchar + "16-bit pixel-value = " + Hex(App.ColorToTGAvalue(newColor)) + "h"
      App.gSpecialColor(ActiveCanvas) = newColor
      CanvasSpecialColors(ActiveCanvas).Backdrop.Graphics.ForeColor = newColor
      CanvasSpecialColors(ActiveCanvas).Backdrop.Graphics.FillRect(0,0,60,30)
      CanvasSpecialColors(ActiveCanvas).Backdrop.Graphics.ForeColor = RGB(0, 0, 0) // black
      CanvasSpecialColors(ActiveCanvas).Backdrop.Graphics.DrawRect(0,0,60,30) // draw a black frame around the picture
    end
  end
  
End Sub

WindowColorSetting.Open:
Sub Open()
  ActiveCanvas = 0 // top canvas is active
  CanvasSpecialColors(ActiveCanvas).SetFocus
  
  // RestoreMafisSettings will be done during launch of the main program
End Sub

WindowColorSetting.CanvasSpecialColors.MouseDown:
Function MouseDown(Index As Integer, X As Integer, Y As Integer) As Boolean
  ActiveCanvas = Index
  me.SetFocus
End Function

WindowColorSetting.PushButtonChange.Action:
Sub Action()
  ChangeColorForActiveCanvas
End Sub

WindowColorSetting.PushButtonRestore.Action:
Sub Action()
  RestoreMafisSettings
End Sub

WindowZFX.ZFXunpacking:
Sub ZFXunpacking()
  const ZFXListMax = 600
  const ZFXmanifestName = "2400BYTE.BIN"
  
  dim InFile As BinaryStream
  dim OutFile As BinaryStream
  dim OutPath As String
  dim OutName As String
  dim dlg1 As OpenDialog
  dim dlg2 As SelectFolderDialog
  dim f1, f2 As FolderItem
  dim count, i, j As Integer
  dim dummy As String
  dim FileSizeErrorCount As Integer
  
  // header and directory description
  dim myNumberOfEntries As Integer
  dim myDirectoryEntry(ZFXListMax) As String
  dim myOffsetTable(ZFXListMax) As Integer
  dim myFileSizeTable(ZFXListMax) As Integer
  
  FileSizeErrorCount = 0
  
  //start user interface
  dlg1 = New OpenDialog
  dlg1.Title = "Select a CC3-ZFX-File for Input"
  dlg1.ActionButtonCaption = "Select"
  dlg1.PromptText = "select a ZFX-file to be splitted into its containing files."
  dlg1.Filter = "special/ZFX;any file"
  f1 = dlg1.ShowModal
  
  if (f1 <> NIL) then
    
    dlg2 = New SelectFolderDialog
    dlg2.Title = "Select Folder for new Files"  
    dlg2.ActionButtonCaption = "Select"
    dlg2.PromptText = "select folder to store the new files."
    dlg2.Filter = "special/folder"
    f2 = dlg2.ShowModal
    
    if (f2 <> NIL) then
      OutPath = f2.AbsolutePath
      #if TargetWin32
        OutPath = OutPath + "\"
      #else
        REM OutPath = OutPath + ":"
      #endif
      
      InFile = f1.OpenAsBinaryFile(FALSE)
      if (InFile <> NIL) then
        if (not InFile.eof) then
          InFile.LittleEndian = TRUE   REM essential, its a PC-born file
          REM first read the header (4 bytes)
          
          myNumberOfEntries = InFile.ReadLong     REM four bytes, number of directory entries
          
          if (myNumberOfEntries > ZFXListMax) then
            MsgBox "more than " + Str(ZFXListMax) + " entries, maybe that it is no ZFX file at all"
          end
          
          // read the directory
          for count = 1 to myNumberOfEntries
            if InFile.EOF then
              dummy = ""
            else
              dummy = InFile.Read(13)   // each directory entry is 13 bytes long = 8 chars + period + 3 ext.chars + nullchar
            end
            myDirectoryEntry(count) = ""
            for i = 1 to 13
              if (Mid(dummy, i, 1) <> Chr(0)) then
                myDirectoryEntry(count) = myDirectoryEntry(count) + Mid(dummy, i, 1)
              end
            next
          next
          
          // read the offset table
          InFile.Position = 7804
          for count = 1 to myNumberOfEntries
            if InFile.EOF then
              myOffsetTable(count) = 0
            else
              myOffsetTable(count) = InFile.ReadLong
            end
          next
          
          // read the next 2400 bytes , called "manifest" by TinTin (4 bytes per entry)
          //OutName = OutPath + ZFXmanifestName
          //f2 = GetFolderItem(OutName)
          
          //if (f2 <> NIL) then
          //#if TargetWin32
          //OutFile = f2.CreateBinaryFile("")
          //#else
          //OutFile = f2.CreateBinaryFile("special/CC2Spriter binary file")
          //#endif
          //OutFile.LittleEndian = TRUE   REM because it is a PC-like binary file
          
          // go to position in file
          //InFile.Position = 10204
          
          // read all bytes
          //if not InFile.EOF then
          //OutFile.Write( InFile.Read(2400) )
          //end
          //OutFile.Close
          //end
          
          // read the filesize table
          InFile.Position = 10204
          for count = 1 to myNumberOfEntries
            if InFile.EOF then
              myFileSizeTable(count) = 0
            else
              myFileSizeTable(count) = InFile.ReadLong
              
              // check for invalid entries of custom ZFXs made by TinTin's tool
              if (myFileSizeTable(count) <= 0) then
                FileSizeErrorCount = FileSizeErrorCount + 1
                if (count >= myNumberOfEntries) then
                  myFileSizeTable(count) = InFile.Length - myOffsetTable(count)  // then read until EOF
                else
                  myFileSizeTable(count) = myOffsetTable(count + 1) - myOffsetTable(count)  // read until next offset starts
                end
              end
            end
          next
          
          if (FileSizeErrorCount > 0) then
            MsgBox( Str(FileSizeErrorCount) + " of " + Str(myNumberOfEntries) + " entries in the file size table contain a zero value. Files' size will be calculated from the offset distances.")
          end
          
          if not InFile.eof then
            ProgressBar1.Visible = TRUE
            ProgressBar1.Value = 0
            ProgressBar1.Maximum = myNumberOfEntries
            ProgressBar1.Refresh
            
            for count = 1 to (myNumberOfEntries - 1)
              ProgressBar1.Value = count
              ProgressBar1.Refresh
              
              // create output file
              OutName = OutPath + myDirectoryEntry(count)
              f2 = GetFolderItem(OutName)
              
              if (f2 <> NIL) then
                #if TargetWin32
                  OutFile = f2.CreateBinaryFile("")
                #else
                  if (Len(OutName) > 4) and ((Uppercase(Right(OutName, 4)) = ".NSD") or (Uppercase(Right(OutName, 4)) = ".ZSD")) then
                    OutFile = f2.CreateBinaryFile("special/CC3sprites")
                  else
                    OutFile = f2.CreateBinaryFile("any file")
                  end
                #endif
                OutFile.LittleEndian = TRUE   REM because it is a PC-like binary file
                
                // go to position in file
                InFile.Position = myOffsetTable(count)
                
                // read all bytes
                //for i = 1 to myOffsetTable(count + 1) - myOffsetTable(count)
                for i = 1 to myFileSizeTable(count)  // new since v2.8.2
                  if not InFile.EOF then
                    OutFile.WriteByte( InFile.ReadByte )
                  end
                next
                
                OutFile.Close
              end
            next
            
            // no process the last entry
            count = myNumberOfEntries
            ProgressBar1.Value = count
            ProgressBar1.Refresh
            OutName = OutPath + myDirectoryEntry(count)
            f2 = GetFolderItem(OutName)
            
            if (f2 <> NIL) then
              #if TargetWin32
                OutFile = f2.CreateBinaryFile("")
              #else
                if (Len(OutName) > 4) and ((Uppercase(Right(OutName, 4)) = ".NSD") or (Uppercase(Right(OutName, 4)) = ".ZSD")) then
                  OutFile = f2.CreateBinaryFile("special/CC3sprites")
                else
                  OutFile = f2.CreateBinaryFile("any file")
                end
              #endif
              OutFile.LittleEndian = TRUE   REM because it is a PC-like binary file, but thats not sure, so we must read byte by byte
              
              // go to position in file
              InFile.Position = myOffsetTable(count)
              
              // read all bytes
              //while not InFile.EOF
              //OutFile.WriteByte( InFile.ReadByte )
              //wend
              for i = 1 to myFileSizeTable(count)  // new since v2.8.2
                if not InFile.EOF then
                  OutFile.WriteByte( InFile.ReadByte )
                end
              next
              
              OutFile.Close
            end
            
            ProgressBar1.Visible = FALSE
          else
            MsgBox "unexpected end of file after header"
          end
          
        else
          MsgBox "empty file: " + f1.Name
        end
        
        InFile.Close
      end
      
    end
  end
  
End Sub

WindowZFX.FXtoTGA:
Sub FXtoTGA(WithAlphaCorrection As Boolean, ExportColorDepth As Integer)
  dim InFile As BinaryStream
  dim OutFile As BinaryStream
  dim InPath As String
  dim OutPath As String
  dim OutName As String
  dim FXDataFile As BinaryStream
  dim dlg1 As OpenDialog
  dim dlg2 As SelectFolderDialog
  dim dlg3 As OpenDialog
  dim f1, f2, f3 As FolderItem
  dim count, i, j As Integer
  dim dummy As String
  
  // FXData header and directory description
  dim FXDataNumberOfEntries As Integer
  dim FXDataEntryIdentified As Integer
  
  // FXData entry description
  dim FXDataEntryNumberOfPictures As Integer
  dim FXDataEntryUnknown2 As Integer
  dim FXDataEntryUnknown3 As Integer
  dim FXDataEntryHotX(200) As Integer
  dim FXDataEntryHotY(200) As Integer
  dim FXDataEntryWidth(200) As Integer
  dim FXDataEntryHeight(200) As Integer
  
  // header and directory description
  dim myNumberOfEntries As Integer
  dim myDirectoryEntry(200) As String
  dim myOffsetTable(200) As Integer
  dim myHotSpotX As Integer
  dim myHotSpotY As Integer
  dim myWidth As Integer
  dim myHeight As Integer
  
  // single pixel
  dim myBlue, myGreen, myRed As Integer
  dim myAlpha As Integer
  
  //start user interface
  dlg1 = New OpenDialog
  dlg1.Title = "Select a CC3/CC4/CC5-FX-File for Input"
  dlg1.ActionButtonCaption = "Select"
  dlg1.PromptText = "select a FX-file to be splitted into its graphics files."
  dlg1.Filter = "any file"
  f1 = dlg1.ShowModal
  
  if (f1 <> NIL) then
    
    InPath = Left(f1.AbsolutePath, Len(f1.AbsolutePath) - Len(f1.Name))
    f3 = GetFolderItem(InPath + "FXData.fx")
    if (f3 = NIL) then
      dlg3 = New OpenDialog
      dlg3.Title = "Select FXData.fx for file headers"
      dlg3.ActionButtonCaption = "Select"
      dlg3.PromptText = "select the file FXData.fx to get the graphics headers."
      dlg3.Filter = "any file"
      f3 = dlg3.ShowModal
    end
    
    if (f3 = NIL) then
      MsgBox "no FXData.fx file found, cannot extract the graphics."
    else
      
      dlg2 = New SelectFolderDialog
      dlg2.Title = "Select Folder for new Files"  
      dlg2.ActionButtonCaption = "Select"
      dlg2.PromptText = "select folder to store the new files."
      dlg2.Filter = "any file"
      if (Len(f1.Name) > 3) then
        dlg2.SuggestedFileName = Left(f1.Name, Len(f1.Name) - 3)
      end
      f2 = dlg2.ShowModal
      
      if (f2 <> NIL) then
        OutPath = f2.AbsolutePath
        #if TargetWin32
          OutPath = OutPath + "\"
        #else
          REM OutPath = OutPath + ":"
        #endif
        
        InFile = f1.OpenAsBinaryFile(FALSE)
        FXDataFile = f3.OpenAsBinaryFile(FALSE)
        if (InFile <> NIL) and (FXDataFile <> NIL) and (not InFile.eof) and (not FXDataFile.eof) then
          InFile.LittleEndian = TRUE   REM essential, its a PC-born file
          FXDataFile.LittleEndian = TRUE   REM essential, its a PC-born file
          
          // identify the filename in FXData.fx
          FXDataFile.Position = 8                                      // skip the first 8 bytes
          FXDataNumberOfEntries = FXDataFile.ReadLong  // 4 bytes
          FXDataEntryIdentified = -1                                // nothing found yet
          // skip the first 3340 bytes of FXData.fx-header
          // each entry then has a fixed size of 1088 bytes
          for count = 1 to FXDataNumberOfEntries
            FXDataFile.Position = 3340 + ((count - 1) * 1088) // here starts the filename of the entry
            dummy = FxDataFile.Read(13)                                // 13 bytes for each filename, padded with zeros
            while (Len(dummy) > 0) and (Mid(dummy, Len(dummy), 1) = Chr(0))
              dummy = Left(dummy, Len(dummy) - 1)              // remove trailing zeros
            wend
            if (dummy = f1.Name) then
              FXDataEntryIdentified = count                            // we have it found
            end
          next
          
          if (FXDataEntryIdentified < 1) then
            MsgBox "sorry, no such entry " + f1.Name + " found inside FXData.fx"
          else
            // get the picture informations
            FXDataFile.Position = 3340 + ((FXDataEntryIdentified - 1) * 1088)   // entry start, filename
            dummy = FXDataFile.Read(32)                                                            // skip the filename and other bytes
            FXDataEntryNumberOfPictures = FXDataFile.ReadLong                       // read the number of entries in this list
            FXDataEntryUnknown2 =  FXDataFile.ReadLong                                   // skip this two unknown values
            FXDataEntryUnknown3 =  FXDataFile.ReadLong
            for i = 1 to FXDataEntryNumberOfPictures
              FXDataEntryHotX(i) = FXDataFile.ReadLong
              FXDataEntryHotY(i) = FXDataFile.ReadLong
            next
            // jump to the next table
            FXDataFile.Position = 3340 + ((FXDataEntryIdentified - 1) * 1088) + 564  // entry start + start of width-table
            FXDataEntryUnknown2 =  FXDataFile.ReadLong                                   // skip this two unknown values
            FXDataEntryUnknown3 =  FXDataFile.ReadLong
            for i = 1 to FXDataEntryNumberOfPictures
              FXDataEntryWidth(i) = FXDataFile.ReadLong
              FXDataEntryHeight(i) = FXDataFile.ReadLong
            next
            
            // read the header of the input file, 12 bytes
            InFile.Position = 8     // skip the first 8 bytes
            myNumberOfEntries = InFile.ReadLong   // 4 bytes
            
            // read the offset table of the input file, has variable length
            for count = 1 to myNumberOfEntries
              myOffsetTable(count) = InFile.ReadLong   // each table entry is 4 bytes, offset from start of datas
              myOffsetTable(count) = myOffsetTable(count) + 12 + (4 * myNumberOfEntries) // recalculate from top of file
            next
            
            // check the contents of the input file
            if (myNumberOfEntries > FXDataEntryNumberOfPictures) then
              MsgBox "more entries in " + f1.Name + " than defined in FXData.fx, output will be truncated."
              myNumberOfEntries = FXDataEntryNumberOfPictures
            end
            
            ProgressBar1.Maximum = myNumberOfEntries
            ProgressBar1.Visible = TRUE
            ProgressBar1.Refresh
            // read all entries in input file
            for count = 1 to myNumberOfEntries
              ProgressBar1.Value = count
              ProgressBar1.Refresh
              
              myHotSpotX = FXDataEntryHotX(count)
              myHotSpotY = FXDataEntryHotY(count)
              myWidth = FXDataEntryWidth(count)
              myHeight = FXDataEntryHeight(count)
              
              // create output filename
              OutName = OutPath + "Image"
              if (count < 10) then
                OutName = OutName + "0"
              end
              if (count < 100) then
                OutName = OutName + "0"
              end
              if (count < 1000) then
                OutName = OutName + "0"
              end
              OutName = OutName + Str(count) + "." + Str(myHotspotX) + "." + Str(myHotspotY) + ".tga"
              
              // create output file
              f2 = GetFolderItem(OutName)
              
              if (f2 <> NIL) then
                #if TargetWin32
                  OutFile = f2.CreateBinaryFile("")
                #else
                  OutFile = f2.CreateBinaryFile("image/x-targa")
                #endif
                OutFile.LittleEndian = TRUE   REM because it is a PC-like TARGA graphics file
                
                // write file - first: the TARGA-header
                OutFile.WriteShort(0)   // no color map
                OutFile.WriteShort(2)   // RGB; +8 means RLE packed
                OutFile.WriteLong(0)    // colormap, no map = 0
                OutFile.WriteLong(0)    // image origin in pixels
                OutFile.WriteShort(myWidth)
                OutFile.WriteShort(myHeight)
                if (ExportColorDepth = 16) then
                  OutFile.WriteByte(16)  // we will always create 16-bit images
                  if RadioButtonTopDown.Value then
                    OutFile.WriteByte(33)
                  else
                    OutFile.WriteByte(1)
                  end
                else
                  OutFile.WriteByte(32)  // only here we will create 32-bit images
                  //OutFile.WriteByte(8)    // as Cpl_Filth did in his ccfx.exe tool, thanks Cpl !
                  if RadioButtonTopDown.Value then
                    OutFile.WriteByte(40)
                  else
                    OutFile.WriteByte(8)
                  end
                end
                
                // now the datas, processing the line offset table
                InFile.Position = myOffsetTable(count) // we have already corrected the offset to top of file
                for i = 1 to myHeight
                  for j = 1 to myWidth
                    myBlue = InFile.ReadByte       // input is 32-bit color graphics with 8-bit alpha channel
                    myGreen = InFile.ReadByte
                    myRed = InFile.ReadByte
                    myAlpha = InFile.ReadByte
                    
                    // we must use Cpl_Filths algorithm of making 32-bit TARGAS
                    // Cpl_Filth's color correction
                    if ( ( 8 * myBlue - 1 ) > 0 ) then
                      myBlue = (8 * myBlue) -1
                    end
                    if ( ( 8 * myGreen - 1 ) > 0 ) then
                      myGreen = (8 * myGreen) -1
                    end
                    if ( ( 8 * myRed - 1 ) > 0 ) then
                      myRed = (8 * myRed) -1
                    end
                    if ( myAlpha <> 0 ) then
                      myAlpha = (8 * myAlpha) -1
                    end
                    
                    if (ExportColorDepth = 16) then
                      if not WithAlphaCorrection then
                        myAlpha = 0
                      end
                      OutFile.WriteShort( App.ColorToTGAvalue( RGB(myBlue + myAlpha, myGreen + myAlpha, myRed + myAlpha) ) )
                    else
                      OutFile.WriteByte(myRed)
                      OutFile.WriteByte(myGreen)
                      OutFile.WriteByte(myBlue)
                      OutFile.WriteByte(myAlpha)
                    end
                  next // pixel
                next // line
                
                OutFile.Close
              end // f2 <> NIL, file was created
            next // processing the entries in InFile
            
            ProgressBar1.Visible = FALSE
            
          end
          FXDataFile.Close
          InFile.Close
        else
          MsgBox "input file(s) are empty."
        end
      end // f2 <> nil
    end // f3 <> nil
  end // f1 <> nil
  
End Sub

WindowZFX.AZPunpacking:
Sub AZPunpacking()
  dim InFile As BinaryStream
  dim OutFile As BinaryStream
  dim OutPath As String
  dim OutName As String
  dim dlg1 As OpenDialog
  dim dlg2 As SelectFolderDialog
  dim f1, f2 As FolderItem
  dim count, i, j As Integer
  dim dummy As String
  
  // header and directory description
  dim myNumberOfEntries As Integer
  dim myDirectoryEntry(600) As String
  dim myOffsetTable(600) As Integer
  dim mySizeTable(600) As Integer
  
  //start user interface
  dlg1 = New OpenDialog
  dlg1.Title = "Select a CC4/CC5-AZP-File for Input"
  dlg1.ActionButtonCaption = "Select"
  dlg1.PromptText = "select a AZP-file to be splitted into its containing files."
  dlg1.Filter = "any file"
  f1 = dlg1.ShowModal
  
  if (f1 <> NIL) then
    
    dlg2 = New SelectFolderDialog
    dlg2.Title = "Select Folder for new Files"  
    dlg2.ActionButtonCaption = "Select"
    dlg2.PromptText = "select folder to store the new files."
    dlg2.Filter = "any file"
    f2 = dlg2.ShowModal
    
    if (f2 <> NIL) then
      OutPath = f2.AbsolutePath
      #if TargetWin32
        OutPath = OutPath + "\"
      #else
        REM OutPath = OutPath + ":"
      #endif
      
      InFile = f1.OpenAsBinaryFile(FALSE)
      if (InFile <> NIL) then
        if (not InFile.eof) then
          InFile.LittleEndian = TRUE   REM essential, its a PC-born file
          REM first read the header (4 bytes)
          
          myNumberOfEntries = InFile.ReadLong     REM four bytes, number of directory entries
          
          if (myNumberOfEntries > 600) then
            MsgBox "more than 600 entries, maybe that it is no AZP file at all"
          end
          
          // read the directory
          for count = 1 to myNumberOfEntries
            dummy = InFile.Read(256)   // each directory entry is 256 bytes long
            myDirectoryEntry(count) = ""
            for i = 1 to 256
              if (Mid(dummy, i, 1) <> Chr(0)) then
                myDirectoryEntry(count) = myDirectoryEntry(count) + Mid(dummy, i, 1)
              end
            next
            
            myOffsetTable(count) = InFile.ReadLong
            mySizeTable(count) = InFile.ReadLong
          next
          
          if not InFile.eof then
            ProgressBar1.Visible = TRUE
            ProgressBar1.Value = 0
            ProgressBar1.Maximum = myNumberOfEntries
            ProgressBar1.Refresh
            
            for count = 1 to myNumberOfEntries
              ProgressBar1.Value = count
              ProgressBar1.Refresh
              
              // create output file
              OutName = OutPath + myDirectoryEntry(count)
              f2 = GetFolderItem(OutName)
              
              if (f2 <> NIL) then
                #if TargetWin32
                  OutFile = f2.CreateBinaryFile("")
                #else
                  OutFile = f2.CreateBinaryFile("any file")
                #endif
                OutFile.LittleEndian = TRUE   REM because it is a PC-like binary file
                
                // go to position in file
                InFile.Position = myOffsetTable(count)
                
                // read all bytes
                for i = 1 to mySizeTable(count)
                  OutFile.WriteByte( InFile.ReadByte )
                next
                
                OutFile.Close
              end
            next
            
            ProgressBar1.Visible = FALSE
          else
            MsgBox "unexpected end of file after header"
          end
          
        else
          MsgBox "empty file: " + f1.Name
        end
        InFile.Close
        
      end
    end
  end
  
End Sub

WindowZFX.TexToTGA:
Sub TexToTGA(Flipped As Boolean, FileNameString As String)
  dim InFile As BinaryStream
  dim OutFile As BinaryStream
  dim OutPath As String
  dim OutName As String
  dim OutFolderName As String
  dim dlg1 As OpenDialog
  dim dlg2 As SelectFolderDialog
  dim f1, f2 As FolderItem
  dim s As String
  dim myFormatId As Integer
  dim myDataSize As Integer
  dim myNumberOfEntries As Integer
  dim myHotpoints(16,3) As Integer   // use of this hotpoints is unknown to me, 4 hotpoints for each image
  dim myWidth(16) As Integer
  dim myHeight(16) As Integer
  dim myOffset(16) As Integer  REM for CC34/5/CCM/RtB-TEX files these offsets are counted from the beginning of the image data!!!
  dim count, i, j As Integer
  dim FormatString As String
  
  Dim cr as String
  
  #if TargetMacOS
    cr=EndOfLine.Macintosh
  #else
    cr=EndOfLine.Windows
  #endif
  
  FormatString = ChrB(0) + ChrB(0) + ChrB(0) + ChrB(0) // usually 0, but can be also 1 .. 3
  myNumberOfEntries = 17 // always fixed size of 17 images
  
  dlg1 = New OpenDialog
  dlg1.Title = "Select a CC4/CC5 *." + FileNameString + " file for Input"
  dlg1.ActionButtonCaption = "Select"
  dlg1.PromptText = "select a *." + FileNameString + "-file to be splitted into TARGA graphics files."
  dlg1.Filter = "special/TEX;any file"
  f1 = dlg1.ShowModal
  
  if (f1 <> NIL) then
    // try to create a folder of nearly the same name as the input file
    if (Uppercase(Right(f1.Name,4)) = ".TEX") then
      OutFolderName = Left(f1.AbsolutePath, Len(f1.AbsolutePath) - 4)
      OutFolderName = App.AddPathDelimiter( OutFolderName )
      f2 = GetFolderItem( OutFolderName )
      f2.CreateAsFolder
      if not f2.Directory then
        f2 = NIL
      end
    elseif (Uppercase(Right(f1.Name,3)) = ".TE") then
      OutFolderName = Left(f1.AbsolutePath, Len(f1.AbsolutePath) - 3)
      OutFolderName = App.AddPathDelimiter( OutFolderName )
      f2 = GetFolderItem( OutFolderName )
      f2.CreateAsFolder
      if not f2.Directory then
        f2 = NIL
      end
    elseif (Uppercase(Right(f1.Name,2)) = ".T") then
      OutFolderName = Left(f1.AbsolutePath, Len(f1.AbsolutePath) - 2)
      OutFolderName = App.AddPathDelimiter( OutFolderName )
      f2 = GetFolderItem( OutFolderName )
      f2.CreateAsFolder
      if not f2.Directory then
        f2 = NIL
      end
    else
      f2 = NIL
    end
    
    // if there is no output folder available yet, create one via dialog
    if (f2 = NIL) then
      dlg2 = New SelectFolderDialog
      dlg2.Title = "Select Folder for new Files"  
      dlg2.ActionButtonCaption = "Select"
      dlg2.PromptText = "select folder to store the new files."
      dlg2.Filter = "special/folder"
      f2 = dlg2.ShowModal
    end
    
    if (f2 <> NIL) then
      OutPath = App.AddPathDelimiter( f2.AbsolutePath )
      
      InFile = f1.OpenAsBinaryFile(FALSE)
      if (InFile <> NIL) then
        if (not InFile.eof) then
          InFile.LittleEndian = TRUE   REM essential, its a PC-born file
          REM first read the header (8 bytes)
          
          myFormatId = InFile.ReadLong     REM four bytes, should be 00000000h
          if (myFormatId > 10) then
            MsgBox "file format may be wrong, header found: " + Hex(myFormatId) + "h"
          end
          
          myDataSize = InFile.ReadLong // size of image data = filesize - 484 bytes
          
          // read the hotpoints table, has always fixed size (17 * 16 = 272 bytes)
          for count = 0 to myNumberOfEntries -1
            for i = 0 to 3
              myHotpoints(count, i) = InFile.ReadLong  // 4 bytes
            next
          next
          
          // read the width / height table, has always fixed size (17 * 8 = 136 bytes)
          for count = 0 to myNumberOfEntries -1
            myWidth(count) = InFile.ReadLong   // 4 bytes
            myHeight(count) = InFile.ReadLong   // 4 bytes
          next
          
          // read the offsets table, has always (17 * 4 = 68 bytes), offsets are counted from top of data area
          for count = 0 to myNumberOfEntries -1
            myOffset(count) = InFile.ReadLong   // 4 bytes
            // add size of header and directory to get the correct offsets of the data
            myOffset(count) = myOffset(count) + 484
          next
          
          // now we read the datas and export them in individual files!
          for count = 0 to myNumberOfEntries - 1
            OutName = "Img"
            if (count < 10) then
              OutName = OutName + "0"
            end
            if (count < 100) then
              OutName = OutName + "0"
            end
            if (count < 1000) then
              OutName = OutName + "0"
            end
            OutName = OutPath + OutName + Str(count) + ".tga"
            
            f2 = GetFolderItem(OutName)
            
            if (f2 <> NIL) then
              #if TargetWin32
                OutFile = f2.CreateBinaryFile("")
              #else
                OutFile = f2.CreateBinaryFile("image/x-targa")
              #endif
              OutFile.LittleEndian = TRUE
              // first: the TARGA-header
              OutFile.WriteShort(0)     // no ID, no color map
              OutFile.WriteShort(2)     // Image Type: uncompressed True-Color
              OutFile.WriteLong(0)      // no color map
              OutFile.WriteLong(0)      // image origin lower left
              OutFile.WriteShort(myWidth(count))
              OutFile.WriteShort(myHeight(count))
              OutFile.WriteByte(16)   // Color Depth 16-bit
              if Flipped then
                OutFile.WriteByte(1)   // Image Descriptor: ignore 1 bit, bottom-to-top and left-to-right pixel orientation
              else
                OutFile.WriteByte(33)   // Image Descriptor: ignore 1 bit, top-to-bottom and left-to-right pixel orientation
              end
              
              if Flipped then
                for i = myHeight(count) downto 1
                  REM from bottom to top stored in the TARGA file
                  InFile.Position = myOffset(count) + ((i - 1) * (myWidth(count) * 2))
                  for j = 1 to myWidth(count)
                    if not InFile.Eof then
                      OutFile.WriteShort( InFile.ReadShort )
                    end
                  next
                next
              else
                InFile.Position = myOffset(count)
                for i = 1 to myHeight(count)
                  for j = 1 to myWidth(count)
                    if not InFile.Eof then
                      OutFile.WriteShort( InFile.ReadShort )
                    end
                  next
                next
              end
              OutFile.Close
              
            end
            
          next
          
          // last: write the hotpoints table
          OutName = OutPath + "HotPoint.txt"
          
          f2 = GetFolderItem(OutName)
          
          if (f2 <> NIL) then
            #if TargetWin32
              OutFile = f2.CreateBinaryFile("")
            #else
              OutFile = f2.CreateBinaryFile("text")
            #endif
            OutFile.LittleEndian = TRUE
            OutFile.Write "// HotPoints table in plain ASCII for the file: " + f1.Name + cr
            OutFile.Write "// Comment lines are possible and will be ignored when repacking TEX file." + cr
            OutFile.Write "// Comment lines can start with / ; :   Blank lines will be ignored, too." + cr
            OutFile.Write "// first entry must be TEX Header-ID (single decimal value, usually 0..3)" + cr
            OutFile.Write Str(myFormatId) + "       // header-ID" + cr
            OutFile.Write "// next 17 lines with 4 hotpoints each" + cr
            for count = 0 to myNumberOfEntries - 1
              for i = 0 to 3 
                OutFile.Write Str( myHotpoints(count, i) ) + " "
              next
              OutFile.Write cr
            next
          end
          
        else
          MsgBox "empty file: " + f1.Name
        end
        InFile.Close
        
      end
      
    end
  end
  
End Sub

WindowZFX.ZFXrepacking:
Sub ZFXrepacking()
  const ZFXListMax = 600
  const ZFXmanifestName = "2400BYTE.BIN"
  
  dim InFile As BinaryStream
  dim OutFile As BinaryStream
  dim dlg2 As SaveAsDialog
  dim dlg1 As SelectFolderDialog
  dim f1, f2, f3 As FolderItem
  dim InPath As String
  dim OutName As String
  dim DirEntries As Integer
  dim count, i As Integer
  dim StoppWorking As Boolean
  
  // header and directory description
  dim myNumberOfEntries As Integer
  dim myDirectoryEntry(ZFXListMax + 1) As String
  dim myOffsetTable(ZFXListMax + 1) As Integer
  dim myFileSizeTable(ZFXListMax + 1) As Integer
  dim my2400Bytes As String
  
  // init tables
  for i = 0 to ZFXListMax + 1
    myDirectoryEntry(i) = ""
    myOffsetTable(i) = 0
    myFileSizeTable(i) = 0
  next
  
  // start user interface
  dlg1 = New SelectFolderDialog
  dlg1.Title = "Select a Folder for Input"
  dlg1.ActionButtonCaption = "Select"
  dlg1.PromptText = "select a folder with the files for re-building new CC3 '*.zfx'-file"
  f1 = dlg1.ShowModal
  
  StoppWorking = FALSE
  myNumberOfEntries = 0
  my2400Bytes = ""
  if (f1 <> NIL) then
    if f1.Exists and f1.Directory and f1.IsReadable then
      InPath = f1.AbsolutePath
      DirEntries = f1.Count
      
      dlg2 = New SaveAsDialog
      dlg2.Title = "Create new File for Output"  
      dlg2.ActionButtonCaption = "Create"
      dlg2.PromptText = "enter name for the new '*.zfx'-file to re-build with " + Str(DirEntries) + " entries"
      dlg2.SuggestedFileName = "new Shadows.zfx"
      dlg2.Filter = "special/zfx;any file"
      f2 = dlg2.ShowModal
      
      if (f2 <> NIL) then
        // init the internal file names table
        for count = 0 to ZFXListMax + 1
          myDirectoryEntry(count) = ""
          myOffsetTable(count) = 0
        next
        myOffsetTable(1) = 4 + (600 * 13) + (600 * 8)  // counted from top of file, always fixed size of 600 entries + 4 bytes header
        
        // first read all filenames and filesizes to collect header infos
        for count = 1 to DirEntries
          if (myNumberOfEntries >= ZFXListMax) then
            MsgBox("more than " + Str(ZFXListMax) + " files found. ZFX archive cannot be created!")
            StoppWorking = TRUE
            Exit  // exit for-loop
          else
            f3 = f1.Item(count)  // FolderItem.Item(#) is one-based (counting start from 1)
            if (f3 <> NIL) then
              if (not f3.Directory) and f3.IsReadable and f3.Visible and (Len(f3.Name) > 0) and (Left(f3.Name,1) <> ".") then
                if (Uppercase(f3.Name) = Uppercase(ZFXmanifestName)) then
                  InFile = f3.OpenAsBinaryFile(FALSE)
                  if (InFile <> NIL) then
                    if (not InFile.Eof) then
                      InFile.LittleEndian = TRUE  // its a PC-born file
                      my2400Bytes = InFile.Read( InFile.Length )  // should be 2400!
                    end
                    InFile.Close
                  end
                else
                  // valid entry
                  myNumberOfEntries = myNumberOfEntries + 1  // we will count from 1, too
                  myDirectoryEntry(myNumberOfEntries) = f3.Name
                  myFileSizeTable(myNumberOfEntries) = f3.Length  // new since v2.8.2
                  if (Len(myDirectoryEntry(myNumberOfEntries)) > 12) then
                    MsgBox("filename longer than 12 chars: '"+ myDirectoryEntry(myNumberOfEntries) + "', ZFX archive cannot be created!")
                    StoppWorking = TRUE
                    Exit  // exit for-loop
                  end
                  myOffsetTable(myNumberOfEntries + 1) = myOffsetTable(myNumberOfEntries) + f3.Length
                end
              end
            end
          end
        next
        myOffsetTable(myNumberOfEntries + 1) = 0
        
        // abort action if there are too many or too few files in folder
        if StoppWorking or (myNumberOfEntries = 0) then
          if (myNumberOfEntries = 0) then
            MsgBox("no valid/readable files found in input folder, no ZFX archive created!")
          end
        else
          // all input is ready
          
          ProgressBar1.Visible = TRUE
          ProgressBar1.Value = 0
          ProgressBar1.Maximum = myNumberOfEntries
          ProgressBar1.refresh
          
          #if TargetWin32
            OutFile = f2.CreateBinaryFile("")
          #else
            OutFile = f2.CreateBinaryFile("special/ZFX")
          #endif
          if (OutFile = NIL) then
            MsgBox "output file cannot be created."
          else
            OutFile.LittleEndian = TRUE  // ZFX are always PC-born files
            
            // write header
            OutFile.WriteLong(myNumberOfEntries)  // number of files in archive
            // write directory
            for count = 1 to ZFXListMax
              if (Len(myDirectoryEntry(count)) > 12) then
                OutFile.Write(Left(myDirectoryEntry(count),12))
                OutFile.WriteByte(0)  // padded with zero
              else
                if (Len(myDirectoryEntry(count)) > 0) then
                  OutFile.Write(myDirectoryEntry(count))
                end
                for i = Len(myDirectoryEntry(count)) + 1 to 13
                  OutFile.WriteByte(0)  // padding with zeros
                next
              end
            next
            // write Offset table
            for count = 1 to ZFXListMax
              OutFile.WriteLong(myOffsetTable(count))
            next
            // write additional unknown table
            //if (Len(my2400Bytes) > 2400) then
            //OutFile.Write(Left(my2400Bytes, 2400))
            //else
            //if (Len(my2400Bytes) > 0) then
            //OutFile.Write(my2400Bytes)
            //end
            //for count = Len(my2400Bytes) + 1 to (ZFXListMax * 4)
            //OutFile.WriteByte(&hFF)
            //next
            //end
            // write FileSize table
            for count = 1 to ZFXListMax
              OutFile.WriteLong(myFileSizeTable(count))
            next
            
            
            // read the files and transfer them without any change into the ZFX
            myNumberOfEntries = 0
            for count = 1 to DirEntries
              if (myNumberOfEntries >= ZFXListMax) then
                Exit  // exit for-loop
              else
                f3 = f1.Item(count)  // FolderItem.Item(#) is one-based (counting start from 1)
                if (f3 <> NIL) then
                  if (not f3.Directory) and f3.IsReadable and f3.Visible and (Len(f3.Name) > 0) and (Left(f3.Name,1) <> ".") then
                    if (Uppercase(f3.Name) = Uppercase(ZFXmanifestName)) then
                    else
                      // valid entry
                      myNumberOfEntries = myNumberOfEntries + 1  // we will count from 1, too
                      ProgressBar1.Value = myNumberOfEntries
                      ProgressBar1.refresh
                      
                      // read the complete file to the ZFX
                      InFile = f3.OpenAsBinaryFile(FALSE)
                      if (InFile <> NIL) then
                        inFile.LittleEndian = TRUE  // its a PC-born file
                        while not InFile.Eof
                          OutFile.WriteByte( InFile.ReadByte )
                        wend
                        
                        InFile.Close
                      end
                    end
                  end
                end
              end
            next
            
            // job done
            OutFile.Close
          end
          
          ProgressBar1.Visible = FALSE
          
        end
      end
    end
  end
  
End Sub

WindowZFX.PushButtonZFXextract.Action:
Sub Action()
  ZFXunpacking
End Sub

WindowZFX.PushButton2.Action:
Sub Action()
  FXtoTGA(TRUE, 16)
End Sub

WindowZFX.PushButton3.Action:
Sub Action()
  FXtoTGA(FALSE, 16)
End Sub

WindowZFX.PushButton4.Action:
Sub Action()
  FXtoTGA(TRUE, 32)
End Sub

WindowZFX.PushButtonAZPextract.Action:
Sub Action()
  AZPunpacking
End Sub

WindowZFX.PushButton6.Action:
Sub Action()
  TexToTGA(RadioButtonFlipped.Value, "tex")
End Sub

WindowZFX.RadioButtonTopDown.Action:
Sub Action()
  RadioButtonFlipped.Value = FALSE
End Sub

WindowZFX.RadioButtonFlipped.Action:
Sub Action()
  RadioButtonTopDown.Value = FALSE
End Sub

WindowZFX.PushButtonZFXrepack.Action:
Sub Action()
  ZFXrepacking
End Sub

WindowAbout.StaticTextVersionText.Open:
Sub Open()
  me.Text = App.gAppVersion
End Sub

WindowAppendixEdit.LoadAppendixFile:
Sub LoadAppendixFile()
  dim InFile As BinaryStream
  dim dlg1 As OpenDialog
  dim f1 As FolderItem
  dim count, i,  b0 As Integer
  dim s As String
  
  // header and directory description
  dim SequenceHeader As String
  dim myNumberOfFrames As Integer
  
  //start user interface
  dlg1 = New OpenDialog
  dlg1.Title = "Select an Appendix.bin-File for Editing"
  dlg1.ActionButtonCaption = "Select"
  dlg1.PromptText = "select a file 'Appendix.bin' to edit its contents."
  dlg1.Filter = "any file"
  f1 = dlg1.ShowModal
  
  if (f1 <> NIL) then
    
    InFile = f1.OpenAsBinaryFile(FALSE)
    if (InFile <> NIL) then
      InFile.LittleEndian = FALSE   REM essential, its a Mac-born file (CC2 + CC3)
      if not InFile.eof then
        // preserve filename for further use
        gListBoxLimitExceeded = FALSE
        gOldAbsolutePath = f1.AbsolutePath
        StaticTextHeader.Text = gOldAbsolutePath
        
        // first read the header (2 bytes)
        SequenceHeader = InFile.Read(2)
        
        // determine byte format
        if (SequenceHeader = (Chr(&hEA) + Chr(&h03))) then
          InFile.LittleEndian = TRUE    // essential, its a PC-born file (CC4, CC5, CCM, RtB)
          gFileFormat = "INTEL"
        elseif (SequenceHeader = (Chr(&h03) + Chr(&hEA))) then
          InFile.LittleEndian = FALSE  // essential, its a Mac-born file (CC2 + CC3)
          gFileFormat = "MOTOROLA"
        else
          MsgBox "its probably no valid 'Appendix.bin' file."
        end
        
        // read entries
        ListBoxStatic.DeleteAllRows
        count = -1
        do
          b0 = InFile.ReadShort
          if (b0 = &h03EB) then
            SequenceHeader = Chr(&h03) + Chr(&hEB)
          else
            count = count + 1
            ListBoxStatic.AddRow(Str(count))
            gUndoStatic(0,count) = Str(count)
            myNumberOfFrames = b0
            ListBoxStatic.Cell( count, 1) = Str(myNumberOfFrames)
            gUndoStatic(1,count) = Str(myNumberOfFrames)
            
            for i = 2 to 4
              b0 = InFile.ReadShort
              if (i = 2) then
                s = "0000" + Hex(b0) 
              else
                s = Hex(b0)
              end
              if (Len(s) > 4) then
                s = Right(s, 4)
              end
              s = s + "h"
              ListBoxStatic.Cell( count, i) = s
              gUndoStatic(i, count) = s
            next
            
            for i = 0 to (myNumberOfFrames - 1)
              b0 = InFile.ReadShort
              if ((5 + i) < ListBoxStatic.ColumnCount) then
                ListBoxStatic.Cell( count, 5 + i) = Str(b0)
              else
                gListBoxLimitExceeded = TRUE
              end
              gUndoStatic(5+i,count) = Str(b0)
            next
          end
        loop until (b0 = &h03EB) or InFile.EOF
        
        gUndoSizeStatic = count + 1
        SetStaticHeaderText( TRUE )
        
        ListboxDirection.DeleteAllRows
        count = -1
        if not InFile.EOF then
          do
            b0 = InFile.ReadShort
            count = count + 1
            ListBoxDirection.AddRow(Str(count))
            gUndoDirection(0,count) = Str(count)
            myNumberOfFrames = b0
            ListBoxDirection.Cell( count, 1) = Str(myNumberOfFrames)
            gUndoDirection(1,count) = Str(myNumberOfFrames)
            
            for i = 2 to 3
              b0 = InFile.ReadShort
              if (i = 2) then
                s = "0000" + Hex(b0) 
              else
                s = Hex(b0)
              end
              if (Len(s) > 4) then
                s = Right(s, 4)
              end
              s = s + "h"
              ListBoxDirection.Cell( count, i) = s
              gUndoDirection(i, count) = s
            next
            
            ListBoxDirection.Cell( count, 4) = "none"
            gUndoDirection(4, count) = "none"
            
            for i = 0 to (myNumberOfFrames - 1)
              b0 = InFile.ReadShort
              if ((5 + i) < ListBoxDirection.ColumnCount) then
                ListBoxDirection.Cell( count, 5 + i) = Str(b0)
              else
                gListBoxLimitExceeded = TRUE
              end
              gUndoDirection(5+i,count) = Str(b0)
            next
          loop until InFile.EOF
        end
        
        gUndoSizeDirection = count + 1
        SetDirectionHeaderText( TRUE )
      else
        MsgBox "empty file: " + f1.Name
      end
      
      InFile.Close
    end
  end
  
  if gListBoxLimitExceeded then
    PushButtonSave.Enabled = FALSE
    PushButtonSaveAs.Enabled = FALSE
    StaticTextLimitExceeded.Text = "file not editable because animation sequence exceeds editor limit."
  else
    PushButtonSave.Enabled = TRUE
    PushButtonSaveAs.Enabled = TRUE
    StaticTextLimitExceeded.Text = ""
  end
  
  if (gFileFormat = "MOTOROLA") then
    PopupMenuEncoding.ListIndex = 1
  else
    PopupMenuEncoding.ListIndex = 0
  end
  
  MarkChanged( FALSE )
  
End Sub

WindowAppendixEdit.PerformAllUndo:
Sub PerformAllUndo()
  dim count, i As Integer
  
  ListBoxStatic.DeleteAllRows
  for count = 0 to gUndoSizeStatic - 1
    ListBoxStatic.AddRow( gUndoStatic(0, count) )
    for i = 1 to (ListBoxStatic.ColumnCount - 1)
      ListBoxStatic.Cell(count,i) = gUndoStatic(i, count)
    next
  next
  
  ListBoxDirection.DeleteAllRows
  for count = 0 to gUndoSizeDirection - 1
    ListBoxDirection.AddRow( gUndoDirection(0, count) )
    for i = 1 to (ListBoxDirection.ColumnCount - 1)
      ListBoxDirection.Cell(count,i) = gUndoDirection(i, count)
    next
  next
  
  StaticTextEA.Text = "static animations (indicator 03EAhex): " + Str(gUndoSizeStatic) + " originally loaded and rebuilded."
  StaticTextEB.Text = "direction-oriented animations (indicator 03EBhex): " + Str(gUndoSizeDirection) + " originally loaded and rebuilded."
  
End Sub

WindowAppendixEdit.SaveListBoxesToAppendixFile:
Sub SaveListBoxesToAppendixFile(TargetFileName As String, myFileFormat As String)
  dim f1 As FolderItem
  dim OutFile As BinaryStream
  dim myNumberOfFrames, b0 As Integer
  dim count, i, j As Integer
  dim s As String
  
  f1 = GetFolderItem( TargetFileName )
  if (f1 = NIL) then
    MsgBox "file cannot be created - no saving done."
  else
    // create output file
    #if TargetWin32
      OutFile = f1.CreateBinaryFile("")
    #else
      OutFile = f1.CreateBinaryFile("special/CC2Spriter binary file")
    #endif
    
    // set byte format for output file
    if (myFileFormat = "MOTOROLA") then
      OutFile.LittleEndian = FALSE       // Mac like
    elseif (myFileFormat = "INTEL") then
      OutFile.LittleEndian = TRUE        // PC like
    else
      OutFile.LittleEndian = FALSE       // Mac like, default
    end
    
    // write &h03EA header
    OutFile.WriteShort( &h03EA )
    
    // write ListBoxStatic
    for count = 0 to ListBoxStatic.ListCount - 1
      myNumberOfFrames = 0
      for i = 5 to (ListBoxStatic.ColumnCount - 1)
        if (ListBoxStatic.Cell(count, i) <> "") then
          myNumberOfFrames = myNumberOfFrames + 1
        end
      next
      if (myNumberOfFrames > Val(ListBoxStatic.Cell(count, 1))) then
        MsgBox "more sprite numbers entered then animation sequence size requires. No: " + Str(count) + " ...corrected"
        ListBoxStatic.Cell(count, 1) = Str(myNumberOfFrames)
      elseif (myNumberOfFrames < Val(ListBoxStatic.Cell(count, 1))) then
        MsgBox "less sprite numbers entered then animation sequence size requires. No: " + Str(count) + " ...corrected"
        ListBoxStatic.Cell(count, 1) = Str(myNumberOfFrames)
      end
      OutFile.WriteShort( myNumberOfFrames )
      
      // style indicator, unknown1, unknown2
      for j = 0 to 2
        b0 = 0
        s = Uppercase(ListBoxStatic.Cell(count, 2 + j))
        for i = 1 to Len(s)
          if (AscB(Mid(s,i,1)) >= AscB("0")) and (AscB(Mid(s,i,1)) <= AscB("9")) then
            b0 = (b0 * 16) + AscB(Mid(s,i,1)) - AscB("0")
          elseif (AscB(Mid(s,i,1)) >= AscB("A")) and (AscB(Mid(s,i,1)) <= AscB("F")) then
            b0 = (b0 * 16) + AscB(Mid(s,i,1)) - AscB("A") + 10
          end
        next
        OutFile.WriteShort( b0 )
      next
      
      // rest of the list
      for i = 5 to (ListBoxStatic.ColumnCount - 1)
        if (ListBoxStatic.Cell(count, i) <> "") then
          OutFile.WriteShort( Val(ListBoxStatic.Cell(count, i)) )
        end
      next
    next // all rows of ListBoxStatic
    
    // write &h03EB header
    OutFile.WriteShort( &h03EB )
    
    // write ListBoxDirection
    for count = 0 to ListBoxDirection.ListCount - 1
      myNumberOfFrames = 0
      for i = 5 to (ListBoxDirection.ColumnCount - 1)
        if (ListBoxDirection.Cell(count, i) <> "") then
          myNumberOfFrames = myNumberOfFrames + 1
        end
      next
      if (myNumberOfFrames > Val(ListBoxDirection.Cell(count, 1))) then
        MsgBox "more sprite numbers entered then animation sequence size requires. No: " + Str(count) + " ...corrected"
        ListBoxDirection.Cell(count, 1) = Str(myNumberOfFrames)
      elseif (myNumberOfFrames < Val(ListBoxDirection.Cell(count, 1))) then
        MsgBox "less sprite numbers entered then animation sequence size requires. No: " + Str(count) + " ...corrected"
        ListBoxDirection.Cell(count, 1) = Str(myNumberOfFrames)
      end
      OutFile.WriteShort( myNumberOfFrames )
      
      // style indicator, unknown1
      for j = 0 to 1
        b0 = 0
        s = Uppercase(ListBoxDirection.Cell(count, 2 + j))
        for i = 1 to Len(s)
          if (AscB(Mid(s,i,1)) >= AscB("0")) and (AscB(Mid(s,i,1)) <= AscB("9")) then
            b0 = (b0 * 16) + AscB(Mid(s,i,1)) - AscB("0")
          elseif (AscB(Mid(s,i,1)) >= AscB("A")) and (AscB(Mid(s,i,1)) <= AscB("F")) then
            b0 = (b0 * 16) + AscB(Mid(s,i,1)) - AscB("A") + 10
          end
        next
        OutFile.WriteShort( b0 )
      next
      
      // rest of the list
      for i = 5 to (ListBoxDirection.ColumnCount - 1)
        if (ListBoxDirection.Cell(count, i) <> "") then
          OutFile.WriteShort( Val(ListBoxDirection.Cell(count, i)) )
        end
      next
    next // all rows of ListBoxDirection
    
    OutFile.Close
    
    MarkChanged( FALSE )
  end
End Sub

WindowAppendixEdit.SaveAppendixFile:
Sub SaveAppendixFile()
  dim f1, f2 As FolderItem
  dim EmptyBackUpSlotFound As Boolean
  dim i As Integer
  
  f1 = GetFolderItem( gOldAbsolutePath )
  if (f1 = NIL) then
    MsgBox "file seems to have gone - no saving at all."
  elseif f1.Locked then
    MsgBox "existing file is locked and cannot be overwritten - no saving at all."
  else
    
    f2 = NIL
    i = 0
    EmptyBackUpSlotFound = FALSE
    while (i < 99) and not EmptyBackUpSlotFound
      i = i + 1
      f2 = GetFolderItem( gOldAbsolutePath + ".backup" + Format(i,"00") + ".bak")
      EmptyBackUpSlotFound = (f2 <> NIL) and (not f2.Exists)
    wend
    
    if (f2 = NIL) or not EmptyBackUpSlotFound then
      MsgBox "backup copy cannot be created. File 'Appendix.bin' will be overwritten."
    else
      f1.MoveFileTo( f2 )
    end
    
    SaveListBoxesToAppendixFile( gOldAbsolutePath, gFileFormat )
  end
End Sub

WindowAppendixEdit.SaveAsNewAppendixFile:
Sub SaveAsNewAppendixFile()
  dim dlg2 As SaveAsDialog
  dim f2 As FolderItem
  
  dlg2 = New SaveAsDialog
  dlg2.Title = "Create new File 'Appendix.bin'"  
  dlg2.ActionButtonCaption = "Save As"
  dlg2.PromptText = "enter place to save the new 'Appendix.bin'."
  dlg2.SuggestedFileName = "Appendix.bin"
  dlg2.Filter = "any file"
  f2 = dlg2.ShowModal
  
  if (f2 <> NIL) then
    select case PopupMenuEncoding.ListIndex
    case 0
      SaveListBoxesToAppendixFile( f2.AbsolutePath, "INTEL" )
    case 1
      SaveListBoxesToAppendixFile( f2.AbsolutePath, "MOTOROLA" )
    end select
  end
  
End Sub

WindowAppendixEdit.PrepareEntryRemoveForUndo:
Sub PrepareEntryRemoveForUndo(StaticList As Boolean, thisLine As Integer)
  dim i As Integer
  
  if StaticList then
    if (thisLine >= 0) and (thisLine < ListBoxStatic.ListCount) then
      gUndoSingleWhichList = 0  // ListBoxStatic
      gUndoSingleWhichLine = thisLine
      for i = 0 to ListBoxStatic.ColumnCount - 1
        gUndoSingleLine(i) = ListBoxStatic.Cell( thisLine, i)
      next
    else
      gUndoSingleWhichList = -1  // invalid
      gUndoSingleWhichLine = -1
    end
  else
    if (thisLine >= 0) and (thisLine < ListBoxDirection.ListCount) then
      gUndoSingleWhichList = 1  // ListBoxDirection
      gUndoSingleWhichLine = thisLine
      for i = 0 to ListBoxDirection.ColumnCount - 1
        gUndoSingleLine(i) = ListBoxDirection.Cell( thisLine, i)
      next
    else
      gUndoSingleWhichList = -1  // invalid
      gUndoSingleWhichLine = -1
    end
  end
End Sub

WindowAppendixEdit.PerformSingleUndo:
Sub PerformSingleUndo()
  // use global vars
  dim i As Integer
  dim thisLine As Integer
  
  thisLine = -1
  if (gUndoSingleWhichList >= 0) and (gUndoSingleWhichLine >= 0) then
    if (gUndoSingleWhichList = 0) then
      // ListBoxStatic
      if (ListBoxStatic.ListCount = 0) then
        ListBoxStatic.AddRow("")
        thisLine = 0
      elseif (ListBoxStatic.ListCount <= gUndoSingleWhichLine) then
        ListBoxStatic.AddRow("")
        thisLine = ListBoxStatic.ListCount - 1
      else
        ListBoxStatic.InsertRow(gUndoSingleWhichLine, "")
        thisLine = gUndoSingleWhichLine
      end
      
      if (thisLine >= 0) and (thisLine < ListBoxStatic.ListCount) then
        for i = 0 to ListBoxStatic.ColumnCount - 1
          ListBoxStatic.Cell(thisLine, i) = gUndoSingleLine(i)
        next
      end
      StaticTextEA.Text = "static animations (indicator 03EAhex): " + Str(gUndoSizeStatic) + " originally loaded, " + Str(ListBoxStatic.ListCount) + " actually defined."
    else
      // ListBoxDirection
      if (ListBoxDirection.ListCount = 0) then
        ListBoxDirection.AddRow("")
        thisLine = 0
      elseif (ListBoxDirection.ListCount <= gUndoSingleWhichLine) then
        ListBoxDirection.AddRow("")
        thisLine = ListBoxDirection.ListCount - 1
      else
        ListBoxDirection.InsertRow(gUndoSingleWhichLine, "")
        thisLine = gUndoSingleWhichLine
      end
      
      if (thisLine >= 0) and (thisLine < ListBoxDirection.ListCount) then
        for i = 0 to ListBoxDirection.ColumnCount - 1
          ListBoxDirection.Cell(thisLine, i) = gUndoSingleLine(i)
        next
      end
      StaticTextEB.Text = "direction-oriented animations (indicator 03EBhex): " + Str(gUndoSizeDirection) + " originally loaded, " + Str(ListBoxDirection.ListCount) + " actually defined."
    end
  end
  
  gUndoSingleWhichLine = -1
  gUndoSingleWhichList = -1
End Sub

WindowAppendixEdit.MarkChanged:
Sub MarkChanged(isChanged As Boolean)
  // added v2.9.2
  
  if (thisChanged <> isChanged) then
    thisChanged = isChanged
    App.SetWindowModified(self, isChanged)
  end
  
End Sub

WindowAppendixEdit.GetStyleValueViaPopUpMenu:
Function GetStyleValueViaPopUpMenu(thisOldEntry As String) As String
  // dim m As New MenuItem
  dim result As String
  
  result = ""
  
  //if (m <> NIL) then
  //m.AddRow("0011h - CC2: play sequence once")
  //m.AddRow("0012h - CC2: loop")
  //m.AddRow("0013h - CC2: back and forth")
  //
  //result = m.Popup
  //end
  
  gpContextualMenuReturnValue = ""
  ContextualMenu1.DeleteAllRows
  ContextualMenu1.AddRow("1100h - CC2: play sequence once")
  ContextualMenu1.AddRow("1200h - CC2: loop")
  ContextualMenu1.AddRow("1300h - CC2: back and forth")
  
  ContextualMenu1.Open
  result = NthField(gpContextualMenuReturnValue, " ", 1)
  gpContextualMenuReturnValue = ""
  
  Return result
End Function

WindowAppendixEdit.SetStaticHeaderText:
Sub SetStaticHeaderText(AfterLoading As Boolean)
  
  if AfterLoading then
    StaticTextEA.Text = "static animation sequences (indicator 03EAhex): " + Str(ListBoxStatic.ListCount) + " loaded"
  else
    StaticTextEA.Text = "static animation sequences (indicator 03EAhex): " + Str(gUndoSizeStatic) + " originally loaded, " + Str(ListBoxStatic.ListCount) + " actually defined."
  end
  
End Sub

WindowAppendixEdit.SetDirectionHeaderText:
Sub SetDirectionHeaderText(AfterLoading As Boolean)
  
  if AfterLoading then
    StaticTextEB.Text = "direction-oriented roto-sprites (indicator 03EBhex): " + Str(ListBoxDirection.ListCount) + " loaded"
  else
    StaticTextEB.Text = "direction-oriented roto-sprites (indicator 03EBhex): " + Str(gUndoSizeDirection) + " originally loaded, " + Str(ListBoxDirection.ListCount) + " actually defined."
  end
  
End Sub

WindowAppendixEdit.EnableMenuItems:
Sub EnableMenuItems()
  EditUndo.Enabled =  (gUndoSingleWhichList >= 0) and (gUndoSingleWhichLine >= 0)
End Sub

WindowAppendixEdit.Resized:
Sub Resized()
  ListBoxStatic.Width = me.Width - 10
  ListBoxStatic.Height = (me.Height - 180) \ 2
  ListBoxDirection.Width = me.Width - 10
  ListBoxDirection.Height = (me.Height - 180) \ 2
  StaticTextEB.Top = ListBoxStatic.Top + ListBoxStatic.Height + 6
  BevelButtonAddAboveDirection.Top = StaticTextEB.Top + 22
  BevelButtonAddBelowDirection.Top = StaticTextEB.Top + 22
  BevelButtonMinusDirection.Top = StaticTextEB.Top + 22
  BevelButtonRenumberDirection.Top = StaticTextEB.Top + 22
  CheckBoxStyleDirection.Top = StaticTextEB.Top + 22
  CheckBoxUnknownDirection.Top = StaticTextEB.Top + 22
  CheckBoxDragReorderDirection.Top = StaticTextEB.Top + 22
  ListBoxDirection.Top = StaticTextEB.Top + 47
  
  PushButtonLoad.Top = me.Height - 46
  PushButtonSave.Top = me.Height - 46
  PushButtonSaveAs.Top = me.Height - 46
  PushButtonUndo.Top = me.Height - 46
  StaticTextLimitExceeded.Top = me.Height - 21
  StaticTextEncoding.Top = me.Height - 46
  PopupMenuEncoding.Top = me.Height - 45
  
  StaticTextHeader.Width = me.Width - StaticTextHeader.Left - 10
End Sub

WindowAppendixEdit.Open:
Sub Open()
  dim i As Integer
  dim s As String
  
  // ListBoxStatic.ColumnCount = 69   // new v2.8.3
  // ListBoxDirection.ColumnCount = 69   // will not work with RB 5.5.4
  
  s = "40,60,70,50,50"
  for i = 5 to (ListBoxStatic.ColumnCount - 1)
    s = s + ",30"
  next
  ListBoxStatic.ColumnWidths = s
  ListBoxStatic.GridLinesVertical = 2 // Thin dotted
  ListBoxStatic.EnableDragReorder = FALSE
  ListBoxStatic.HasHeading = TRUE
  ListBoxStatic.Heading(0) = "No"
  ListBoxStatic.Heading(1) = "Entries"
  ListBoxStatic.Heading(2) = "Style"
  ListBoxStatic.Heading(3) = "U_1"
  ListBoxStatic.Heading(4) = "U_2"
  ListBoxStatic.ColumnAlignment(0) = 3 // Right
  ListBoxStatic.ColumnAlignment(1) = 3 // Right
  ListBoxStatic.ColumnAlignment(2) = 2 // Center
  ListBoxStatic.ColumnAlignment(3) = 3 // Right
  ListBoxStatic.ColumnAlignment(4) = 3 // Right
  ListBoxStatic.ColumnType(0) = 1 // Normal
  ListBoxStatic.ColumnType(1) = 3 // Editable
  ListBoxStatic.ColumnType(2) = 1 // Normal
  ListBoxStatic.ColumnType(3) = 1 // Normal
  ListBoxStatic.ColumnType(4) = 1 // Normal
  for i = 5 to (ListBoxStatic.ColumnCount - 1)
    ListBoxStatic.Heading(i) = "#" + Str(i - 5)
    ListBoxStatic.ColumnAlignment(i) = 3 // Right
    ListBoxStatic.ColumnType(i) = 3 // Editable
  next
  
  ListBoxDirection.ColumnWidths = s
  ListBoxDirection.GridLinesVertical = 2 // Thin dotted
  ListBoxDirection.EnableDragReorder = FALSE
  ListBoxDirection.HasHeading = TRUE
  ListBoxDirection.Heading(0) = "No"
  ListBoxDirection.Heading(1) = "Entries"
  ListBoxDirection.Heading(2) = "Style"
  ListBoxDirection.Heading(3) = "U_1"
  ListBoxDirection.Heading(4) = "U_2"
  ListBoxDirection.ColumnAlignment(0) = 3 // Right
  ListBoxDirection.ColumnAlignment(1) = 3 // Right
  ListBoxDirection.ColumnAlignment(2) = 2 // Center
  ListBoxDirection.ColumnAlignment(3) = 3 // Right
  ListBoxDirection.ColumnAlignment(4) = 3 // Right
  ListBoxDirection.ColumnType(0) = 1 // Normal
  ListBoxDirection.ColumnType(1) = 3 // Editable
  ListBoxDirection.ColumnType(2) = 1 // Normal
  ListBoxDirection.ColumnType(3) = 1 // Normal
  ListBoxDirection.ColumnType(4) = 1 // Normal
  for i = 5 to (ListBoxDirection.ColumnCount - 1)
    ListBoxDirection.Heading(i) = "#" + Str(i - 5)
    ListBoxDirection.ColumnAlignment(i) = 3 // Right
    ListBoxDirection.ColumnType(i) = 3 // Editable
  next
  
  gUndoSingleWhichList = -1  // no undo line present
  gUndoSingleWhichLine = -1  // no undo line present
  
  thisChanged = FALSE
  thisListBoxHasFocus = NIL
  gpContextualMenuReturnValue = ""
  
End Sub

WindowAppendixEdit.PushButtonLoad.Action:
Sub Action()
  LoadAppendixFile
End Sub

WindowAppendixEdit.PushButtonSave.Action:
Sub Action()
  SaveAppendixFile
End Sub

WindowAppendixEdit.PushButtonSaveAs.Action:
Sub Action()
  SaveAsNewAppendixFile
End Sub

WindowAppendixEdit.PushButtonUndo.Action:
Sub Action()
  PerformAllUndo
End Sub

WindowAppendixEdit.ListBoxStatic.GotFocus:
Sub GotFocus()
  thisListBoxHasFocus = me
End Sub

WindowAppendixEdit.ListBoxStatic.CellClick:
Function CellClick(row as Integer, column as Integer, x as Integer, y as Integer) As Boolean
  dim oldValue As String
  
  if (row >= 0) and (row < me.ListCount) and (App.gBlackTriangleForMenu <> NIL) then
    if (column = 2) then   // "Style" column
      // look where we are within this column
      
      me.ListIndex = row
      me.Refresh
      
      if (x >= me.Column(column).WidthActual - 2 - App.gBlackTriangleForMenu.Width) then
        oldValue = me.Cell(row, column)
        
        me.Cell(row, column) = GetStyleValueViaPopUpMenu(oldValue)
        if (me.Cell(row, column) = "") then
          me.Cell(row, column) = oldValue
          me.EditCell(row, column)
        end
        if (oldValue <> me.Cell(row, column)) then
          // changed, indicate with color
          me.CellBold(row,column) = TRUE
        end
        
      else
        me.EditCell(row, column)
      end
      
      // we have finished
      Return TRUE
      
    else
      // lets process the listbox
      Return FALSE
    end
    
  else
    // lets process the listbox
    Return FALSE
  end
  
End Function

WindowAppendixEdit.ListBoxStatic.CellTextChange:
Sub CellTextChange(row as Integer, column as Integer)
  MarkChanged( TRUE )
End Sub

WindowAppendixEdit.ListBoxStatic.SortColumn:
Function SortColumn(column As Integer) As Boolean
  MarkChanged( TRUE )
End Function

WindowAppendixEdit.ListBoxStatic.CellBackgroundPaint:
Function CellBackgroundPaint(g As Graphics, row As Integer, column As Integer) As Boolean
  // added v2.9.2
  
  if (row = me.ListIndex) or me.Selected(row) then
    if (thisListBoxHasFocus = me) then
      g.foreColor = &c4D66F0
    else
      g.foreColor = &cD0D0D0
    end
    g.FillRect(0,0,g.width,g.height - 1)
  elseIf row Mod 2=0 then
    g.foreColor = &cF0F0F0
    g.FillRect(0,0,g.width,g.height)
  else
    g.foreColor = &cFFFFFF
    g.FillRect(0,0,g.width,g.height)
  end if
  
  if (row >= 0) and (row < me.ListCount) then
    if (column = 2) and (App.gBlackTriangleForMenu <> NIL) then
      g.DrawPicture(App.gBlackTriangleForMenu, g.Width - App.gBlackTriangleForMenu.Width - 2, 0)
    end
  end
  
  Return TRUE // we do the entire painting
End Function

WindowAppendixEdit.ListBoxStatic.CompareRows:
Function CompareRows(row1 as Integer, row2 as Integer, column as Integer, ByRef result as Integer) As Boolean
  // added v2.9.2
  
  dim myCompare1, myCompare2 As Integer
  dim goOn As Boolean
  
  if (Uppercase(Left(Me.Cell(row1,column), 2)) = "0X") or (Uppercase(Right(Me.Cell(row1,column), 1)) = "H") then
    myCompare1 = App.HexToInt( Me.Cell(row1,column) )
    goOn = TRUE
  elseif App.gmIsNumerical( Me.Cell(row1,column) ) then
    myCompare1 = Val( Me.Cell(row1,column) )
    goOn = TRUE
  else
    goOn = FALSE
  end
  
  if goOn then
    if (Uppercase(Left(Me.Cell(row2,column), 2)) = "0X") or (Uppercase(Right(Me.Cell(row2,column), 1)) = "H") then
      myCompare2 = App.HexToInt( Me.Cell(row2,column) )
      goOn = TRUE
    elseif App.gmIsNumerical( Me.Cell(row2,column) ) then
      myCompare2 = Val( Me.Cell(row2,column) )
      goOn = TRUE
    else
      goOn = FALSE
    end
  end
  
  if goOn then
    
    If (myCompare1 > myCompare2) then
      result=1
    else
      result=-1
    End if
    Return TRUE  //tells RB to use the custom sort
    
  else
    Return FALSE
  end
  
  
End Function

WindowAppendixEdit.ListBoxStatic.HeaderPressed:
Function HeaderPressed(column as Integer) As Boolean
  Return FALSE  // enable sorting, new v2.9.2
End Function

WindowAppendixEdit.ListBoxStatic.CellAction:
Sub CellAction(row As Integer, column As Integer)
  dim s As String
  
  // correct hex-view
  if (column = 2) then
    s = me.Cell(row,column)
    if (Len(s) = 0) then
      me.Cell(row,column) = "0000h"
    else
      if (Uppercase(Right(s,1)) <> "H") then
        me.Cell(row,column) = Hex(Val(s)) + "h"
      end
    end
  end
  
  // changed, indicate with color
  me.CellBold(row,column) = TRUE
End Sub

WindowAppendixEdit.ListBoxDirection.GotFocus:
Sub GotFocus()
  thisListBoxHasFocus = me
End Sub

WindowAppendixEdit.ListBoxDirection.CellTextChange:
Sub CellTextChange(row as Integer, column as Integer)
  MarkChanged( TRUE )
End Sub

WindowAppendixEdit.ListBoxDirection.SortColumn:
Function SortColumn(column As Integer) As Boolean
  MarkChanged( TRUE )
End Function

WindowAppendixEdit.ListBoxDirection.CellBackgroundPaint:
Function CellBackgroundPaint(g As Graphics, row As Integer, column As Integer) As Boolean
  // added v2.9.2
  
  if (row = me.ListIndex) or me.Selected(row) then
    if (thisListBoxHasFocus = me) then
      g.foreColor = &c4D66F0
    else
      g.foreColor = &cD0D0D0
    end
    g.FillRect(0,0,g.width,g.height - 1)
  elseIf row Mod 2=0 then
    g.foreColor = &cF0F0F0
    g.FillRect(0,0,g.width,g.height)
  else
    g.foreColor = &cFFFFFF
    g.FillRect(0,0,g.width,g.height)
  end if
  
  Return TRUE
End Function

WindowAppendixEdit.ListBoxDirection.CompareRows:
Function CompareRows(row1 as Integer, row2 as Integer, column as Integer, ByRef result as Integer) As Boolean
  // added v2.9.2
  
  dim myCompare1, myCompare2 As Integer
  dim goOn As Boolean
  
  if (Uppercase(Left(Me.Cell(row1,column), 2)) = "0X") or (Uppercase(Right(Me.Cell(row1,column), 1)) = "H") then
    myCompare1 = App.HexToInt( Me.Cell(row1,column) )
    goOn = TRUE
  elseif App.gmIsNumerical( Me.Cell(row1,column) ) then
    myCompare1 = Val( Me.Cell(row1,column) )
    goOn = TRUE
  else
    goOn = FALSE
  end
  
  if goOn then
    if (Uppercase(Left(Me.Cell(row2,column), 2)) = "0X") or (Uppercase(Right(Me.Cell(row2,column), 1)) = "H") then
      myCompare2 = App.HexToInt( Me.Cell(row2,column) )
      goOn = TRUE
    elseif App.gmIsNumerical( Me.Cell(row2,column) ) then
      myCompare2 = Val( Me.Cell(row2,column) )
      goOn = TRUE
    else
      goOn = FALSE
    end
  end
  
  if goOn then
    
    If (myCompare1 > myCompare2) then
      result=1
    else
      result=-1
    End if
    Return TRUE  //tells RB to use the custom sort
    
  else
    Return FALSE
  end
  
  
End Function

WindowAppendixEdit.ListBoxDirection.HeaderPressed:
Function HeaderPressed(column as Integer) As Boolean
  Return FALSE  // enable sorting, new v2.9.2
End Function

WindowAppendixEdit.ListBoxDirection.CellAction:
Sub CellAction(row As Integer, column As Integer)
  dim s As String
  
  // correct hex-view
  if (column = 2) then
    s = me.Cell(row,column)
    if (Len(s) = 0) then
      me.Cell(row,column) = "0000h"
    else
      if (Uppercase(Right(s,1)) <> "H") then
        me.Cell(row,column) = Hex(Val(s)) + "h"
      end
    end
  end
  
  // changed, indicate with color
  me.CellBold(row,column) = TRUE
End Sub

WindowAppendixEdit.CheckBoxStyleStatic.Action:
Sub Action()
  if me.Value then
    ListBoxStatic.ColumnType(2) = 3 // Editable
  else
    ListBoxStatic.ColumnType(2) = 1 // non Editable
  end
End Sub

WindowAppendixEdit.CheckBoxUnknownStatic.Action:
Sub Action()
  if me.Value then
    ListBoxStatic.ColumnType(3) = 3 // Editable
    ListBoxStatic.ColumnType(4) = 3 // Editable
  else
    ListBoxStatic.ColumnType(3) = 1 // non Editable
    ListBoxStatic.ColumnType(4) = 1 // non Editable
  end
End Sub

WindowAppendixEdit.BevelButtonAddBelowStatic.Action:
Sub Action()
  if (ListBoxStatic <> NIL) then
    ListBoxStatic.SetFocus
    if (ListBoxStatic.ListCount <= 0) then
      ListBoxStatic.AddRow("new")
      ListBoxStatic.ListIndex = 0
      ListBoxStatic.Cell( ListBoxStatic.ListIndex, 1) = "0"
      ListBoxStatic.Cell( ListBoxStatic.ListIndex, 2) = "1100h"
      ListBoxStatic.Cell( ListBoxStatic.ListIndex, 3) = "0h"
      ListBoxStatic.Cell( ListBoxStatic.ListIndex, 4) = "0h"
    elseif (ListBoxStatic.ListIndex >= 0) and (ListBoxStatic.ListIndex < ListBoxStatic.ListCount) then
      ListBoxStatic.InsertRow( ListBoxStatic.ListIndex + 1, "new")
      ListBoxStatic.Cell( ListBoxStatic.ListIndex + 1, 1) = "0"
      ListBoxStatic.Cell( ListBoxStatic.ListIndex + 1, 2) = "1100h"
      ListBoxStatic.Cell( ListBoxStatic.ListIndex + 1, 3) = "0h"
      ListBoxStatic.Cell( ListBoxStatic.ListIndex + 1, 4) = "0h"
    end
    SetStaticHeaderText( FALSE )
    MarkChanged( TRUE )
  end
End Sub

WindowAppendixEdit.BevelButtonAddAboveStatic.Action:
Sub Action()
  if (ListBoxStatic <> NIL) then
    ListBoxStatic.SetFocus
    if (ListBoxStatic.ListCount <= 0) then
      ListBoxStatic.AddRow("new")
      ListBoxStatic.ListIndex = 0
      ListBoxStatic.Cell( ListBoxStatic.ListIndex, 1) = "0"
      ListBoxStatic.Cell( ListBoxStatic.ListIndex, 2) = "1100h"
      ListBoxStatic.Cell( ListBoxStatic.ListIndex, 3) = "0h"
      ListBoxStatic.Cell( ListBoxStatic.ListIndex, 4) = "0h"
    elseif (ListBoxStatic.ListIndex >= 0) and (ListBoxStatic.ListIndex < ListBoxStatic.ListCount) then
      ListBoxStatic.InsertRow( ListBoxStatic.ListIndex, "new")
      ListBoxStatic.Cell( ListBoxStatic.ListIndex - 1, 1) = "0"
      ListBoxStatic.Cell( ListBoxStatic.ListIndex - 1, 2) = "1100h"
      ListBoxStatic.Cell( ListBoxStatic.ListIndex - 1, 3) = "0h"
      ListBoxStatic.Cell( ListBoxStatic.ListIndex - 1, 4) = "0h"
    end
    SetStaticHeaderText( FALSE )
    MarkChanged( TRUE )
  end
End Sub

WindowAppendixEdit.BevelButtonMinusStatic.Action:
Sub Action()
  if (ListBoxStatic <> NIL) then
    ListBoxStatic.SetFocus
    if (ListBoxStatic.ListIndex >= 0) and (ListBoxStatic.ListIndex < ListBoxStatic.ListCount) then
      PrepareEntryRemoveForUndo(TRUE, ListBoxStatic.ListIndex )
      ListBoxStatic.RemoveRow( ListBoxStatic.ListIndex )
      SetStaticHeaderText( FALSE )
      MarkChanged( TRUE )
    else
      Beep
    end
  end
End Sub

WindowAppendixEdit.BevelButtonAddBelowDirection.Action:
Sub Action()
  if (ListBoxDirection <> NIL) then
    ListBoxDirection.SetFocus
    if (ListBoxDirection.ListCount <= 0) then
      ListBoxDirection.AddRow("new")
      ListBoxDirection.ListIndex = 0
      ListBoxDirection.Cell( ListBoxDirection.ListIndex, 1) = "0"
      ListBoxDirection.Cell( ListBoxDirection.ListIndex, 2) = "0h"
      ListBoxDirection.Cell( ListBoxDirection.ListIndex, 3) = "0h"
      ListBoxDirection.Cell( ListBoxDirection.ListIndex, 4) = "none"
    elseif (ListBoxDirection.ListIndex >= 0) and (ListBoxDirection.ListIndex < ListBoxDirection.ListCount) then
      ListBoxDirection.InsertRow( ListBoxDirection.ListIndex + 1, "new")
      ListBoxDirection.Cell( ListBoxDirection.ListIndex + 1, 1) = "0"
      ListBoxDirection.Cell( ListBoxDirection.ListIndex + 1, 2) = "0h"
      ListBoxDirection.Cell( ListBoxDirection.ListIndex + 1, 3) = "0h"
      ListBoxDirection.Cell( ListBoxDirection.ListIndex + 1, 4) = "none"
    end
    SetDirectionHeaderText( FALSE )
    MarkChanged( TRUE )
  end
End Sub

WindowAppendixEdit.BevelButtonAddAboveDirection.Action:
Sub Action()
  if (ListBoxDirection <> NIL) then
    ListBoxDirection.SetFocus
    if (ListBoxDirection.ListCount <= 0) then
      ListBoxDirection.AddRow("new")
      ListBoxDirection.ListIndex = 0
      ListBoxDirection.Cell( ListBoxDirection.ListIndex, 1) = "0"
      ListBoxDirection.Cell( ListBoxDirection.ListIndex, 2) = "0h"
      ListBoxDirection.Cell( ListBoxDirection.ListIndex, 3) = "0h"
      ListBoxDirection.Cell( ListBoxDirection.ListIndex, 4) = "none"
    elseif (ListBoxDirection.ListIndex >= 0) and (ListBoxDirection.ListIndex < ListBoxDirection.ListCount) then
      ListBoxDirection.InsertRow( ListBoxDirection.ListIndex, "new")
      ListBoxDirection.Cell( ListBoxDirection.ListIndex - 1, 1) = "0"
      ListBoxDirection.Cell( ListBoxDirection.ListIndex - 1, 2) = "0h"
      ListBoxDirection.Cell( ListBoxDirection.ListIndex - 1, 3) = "0h"
      ListBoxDirection.Cell( ListBoxDirection.ListIndex - 1, 4) = "none"
    end
    SetDirectionHeaderText( FALSE )
    MarkChanged( TRUE )
  end
End Sub

WindowAppendixEdit.BevelButtonMinusDirection.Action:
Sub Action()
  if (ListBoxDirection <> NIL) then
    ListBoxDirection.SetFocus
    if (ListBoxDirection.ListIndex >= 0) and (ListBoxDirection.ListIndex < ListBoxDirection.ListCount) then
      PrepareEntryRemoveForUndo(FALSE, ListBoxDirection.ListIndex )
      ListBoxDirection.RemoveRow( ListBoxDirection.ListIndex )
      SetDirectionHeaderText( FALSE )
      MarkChanged( TRUE )
    else
      Beep
    end
  end
End Sub

WindowAppendixEdit.BevelButtonRenumberStatic.Action:
Sub Action()
  dim i As Integer
  
  if (ListBoxStatic <> NIL) then
    ListBoxStatic.SetFocus
    for i = 0 to ListBoxStatic.ListCount - 1
      ListBoxStatic.Cell(i, 0) = Str(i)
    next
    MarkChanged( TRUE )
  end
  
End Sub

WindowAppendixEdit.BevelButtonRenumberDirection.Action:
Sub Action()
  dim i As Integer
  
  if (ListBoxDirection <> NIL) then
    ListBoxDirection.SetFocus
    for i = 0 to ListBoxDirection.ListCount - 1
      ListBoxDirection.Cell(i, 0) = Str(i)
    next
    MarkChanged( TRUE )
  end
  
End Sub

WindowAppendixEdit.CheckBoxStyleDirection.Action:
Sub Action()
  if me.Value then
    ListBoxDirection.ColumnType(2) = 3 // Editable
  else
    ListBoxDirection.ColumnType(2) = 1 // non Editable
  end
End Sub

WindowAppendixEdit.CheckBoxUnknownDirection.Action:
Sub Action()
  if me.Value then
    ListBoxDirection.ColumnType(3) = 3 // Editable
    ListBoxDirection.ColumnType(4) = 1 // non Editable, because not available
  else
    ListBoxDirection.ColumnType(3) = 1 // non Editable
    ListBoxDirection.ColumnType(4) = 1 // non Editable, because not available
  end
End Sub

WindowAppendixEdit.PopupMenuEncoding.Change:
Sub Change()
  if (gFileFormat = "MOTOROLA") and (me.ListIndex = 1) then
    PushButtonSave.Enabled = TRUE
  elseif (gFileFormat = "INTEL") and (me.ListIndex = 0) then
    PushButtonSave.Enabled = TRUE
  else
    PushButtonSave.Enabled = FALSE
  end
End Sub

WindowAppendixEdit.CheckBoxDragReorderStatic.Action:
Sub Action()
  dim i As Integer
  
  if me.Value then
    // make everything non-editable
    ListBoxStatic.EnabledragReorder = TRUE
    for i = 0 to ListBoxStatic.ColumnCount - 1
      ListBoxStatic.ColumnType(i) = 1 // non Editable
    next
    
  else
    // make editable what should be editable
    ListBoxStatic.EnabledragReorder = FALSE
    for i = 0 to 1
      ListBoxStatic.ColumnType(i) = 3 // Editable
    next
    if CheckBoxStyleStatic.Value then
      ListBoxStatic.ColumnType(2) = 3 // Editable
    else
      ListBoxStatic.ColumnType(2) = 1 // non Editable
    end
    if CheckBoxUnknownStatic.Value then
      ListBoxStatic.ColumnType(3) = 3 // Editable
      ListBoxStatic.ColumnType(4) = 3 // Editable
    else
      ListBoxStatic.ColumnType(3) = 1 // non Editable
      ListBoxStatic.ColumnType(4) = 1 // non Editable
    end
    for i = 5 to ListBoxStatic.ColumnCount - 1
      ListBoxStatic.ColumnType(i) = 3 // Editable
    next
    
  end
End Sub

WindowAppendixEdit.CheckBoxDragReorderDirection.Action:
Sub Action()
  dim i As Integer
  
  if me.Value then
    // make everything non-editable
    ListBoxDirection.EnabledragReorder = TRUE
    for i = 0 to ListBoxDirection.ColumnCount - 1
      ListBoxDirection.ColumnType(i) = 1 // non Editable
    next
    
  else
    // make editable what should be editable
    ListBoxDirection.EnabledragReorder = FALSE
    for i = 0 to 1
      ListBoxDirection.ColumnType(i) = 3 // Editable
    next
    if CheckBoxStyleDirection.Value then
      ListBoxDirection.ColumnType(2) = 3 // Editable
    else
      ListBoxDirection.ColumnType(2) = 1 // non Editable
    end
    if CheckBoxUnknownDirection.Value then
      ListBoxDirection.ColumnType(3) = 3 // Editable
      ListBoxDirection.ColumnType(4) = 1 // non Editable, because not available
    else
      ListBoxDirection.ColumnType(3) = 1 // non Editable
      ListBoxDirection.ColumnType(4) = 1 // non Editable
    end
    for i = 5 to ListBoxDirection.ColumnCount - 1
      ListBoxDirection.ColumnType(i) = 3 // Editable
    next
    
  end
End Sub

WindowAppendixEdit.ContextualMenu1.Action:
Sub Action(item As String)
  gpContextualMenuReturnValue = item
End Sub

WindowSoldierColors.Open:
Sub Open()
  dim i As Integer
  dim CRchar As String
  dim newColor As Color
  
  #if TargetWin32
    CRchar = Chr(13) + Chr(10)
  #else
    CRchar = Chr(13)
  #endif
  
  for i = 0 to 9
    newColor = App.TGAvalueToColor( (i * 1500) + 5000 )
    ValuesSpecialColors(i).Text = Left(ValuesSpecialColors(i).Text, 21) + CRchar + "RGB value=(" + Hex(newColor.Red) + "h, " + Hex(newColor.Green) + "h, " + Hex(newColor.Blue) + "h)"
    ValuesSpecialColors(i).Text = ValuesSpecialColors(i).Text + CRchar + "16-bit pixel-value = " + Hex(App.ColorToTGAvalue(newColor)) + "h"
    CanvasSpecialColors(i).Backdrop = NewPicture(CanvasSpecialColors(i).Width, CanvasSpecialColors(i).Height, 16)
    if (CanvasSpecialColors(i) <> NIL) and (CanvasSpecialColors(i).Backdrop <> NIL) and (CanvasSpecialColors(i).Backdrop.Graphics <> NIL) then
      CanvasSpecialColors(i).Backdrop.Graphics.ForeColor = newColor
      CanvasSpecialColors(i).Backdrop.Graphics.FillRect(0,0,60,30)
      CanvasSpecialColors(i).Backdrop.Graphics.ForeColor = RGB(0, 0, 0) // black
      CanvasSpecialColors(i).Backdrop.Graphics.DrawRect(0,0,60,30) // draw a black frame around the picture
    end
  next
  
  ActiveCanvas = 0
End Sub

WindowSoldierColors.CanvasSpecialColors.MouseDown:
Function MouseDown(Index As Integer, X As Integer, Y As Integer) As Boolean
  ActiveCanvas = Index
  me.SetFocus
End Function

